DataGridView数据绑定

时间:2013-01-10 20:12:06

标签: c# data-binding datagridview datagridviewcomboboxcell

我举一个简单的例子来解释我想要的东西:

我定义了一个名为Student的类,它有两个属性: Name Subjects

public class Student()
{
     public string Name;
     public List<string> Subjects;
}

我创建了两个Student类实例,例如:

List<string> jackSubjects = new List<string>();
jackSubjects.Add("Math");
jackSubjects.Add("Physics");
Student Jack = new Student("Jack", jackSubjects);
List<string> alanSubjects = new List<string>();
alanSubjects.Add("Accounting");
alanSubjects.Add("Science");
Student Alan = new Student("Alan", alanSubjects);

然后我创建一个List studentList:

List<Student> studentList = new List<Student>();
studentList.Add(Jack);
studentList.Add(Alan);

我的问题是,有什么方法可以用studentListDataGridView进行数据绑定,如下所示:

dataGridView.DataSource = studentList;

第一列是学生姓名,第二列是combobox,显示学生的所有科目。

感谢您提前抽出时间。

1 个答案:

答案 0 :(得分:1)

这样的事情会起作用:

  1. 向网格添加RowDataBound事件并创建模板列以保存主题的下拉列表:

    <asp:GridView ID="dataGridView" runat="server" AutoGenerateColumns="false" OnRowDataBound="dataGridView_RowDataBound">
       <Columns>
           <asp:BoundField DataField="Name" />
           <asp:TemplateField>
               <ItemTemplate>
                   <asp:DropDownList ID="subjects" runat="server" ></asp:DropDownList>
               </ItemTemplate>
           </asp:TemplateField>
       </Columns>
    

  2. 然后在代码后面处理RowDataBound事件:

    protected void dataGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
        var ddl = (e.Row.FindControl("subjects") as DropDownList);
        ddl.DataSource = (e.Row.DataItem as Student).Subjects;
        ddl.DataBind();
      }
    }
    
  3. 渲染: enter image description here

    顺便说一句,你的学生班应该是这样的:

    public class Student
    {
         public string Name {get;set;}
         public List<string> Subjects {get;set;}
    
         public Student(string name, List<string> subjects)
         {
             Name = name;
             Subjects = subjects;
         }
    }