从列表中获取特定属性

时间:2014-02-08 20:02:54

标签: c# winforms datagridview

我正面临一个问题

我有一个班级

public class StudentDetails
{    
    int S_Detail_ID;
    string address;
    string email;    
}

包含get set方法和iam调用正在收集List<StudentDetails>的函数并在datagridview中显示它的问题是list返回了类的所有属性,但我只想要地址和电子邮件而不是s_detail_id

这是函数的代码

private void btnAddNewRowInGrid_Click(object sender, EventArgs e) 
{

    List<StudentDetails> lstStudentDetails = GetStudentDetails();
    lststudentDetails.Add(new StudentDetails()); //what to do here, studentDetails is returning all properties but i want only addres and email
    dataGridView1.DataSource = lstStudentDetails;
} 

和GetStudent jusst计算datagridview中的行并添加新行

private List<StudentDetails> GetStudentDetails()
{
    lstStudentDetails = new List<StudentDetails>();
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {

        lstStudentDetails.Add(row.DataBoundItem as StudentDetails);
    }
    return lstStudentDetails;
}

2 个答案:

答案 0 :(得分:3)

  1. 在设计器中选择DataGridView,然后单击控件右上角的小三角形
  2. 点击编辑列菜单项
  3. 手动添加地址和电子邮件属性列(在列属性的DataPropertyName项中键入属性名称)
  4. 禁用列自动生成
  5. enter image description here

    您无法关闭设计器中的列自动生成 - 只能从代码中删除:

    dataGridView1.AutoGenerateColumns = false;
    

    之后你的代码就可以了。

答案 1 :(得分:0)

您可以尝试通过将其可见性设置为false来隐藏您不需要的列。

dataGridView1.Columns["S_Detail_ID"].Visible = false;
相关问题