DataGridView databinding

怎甘沉沦 提交于 2019-12-10 19:52:20

问题


I give a simple example to explain what I want:

I defined a class called Student, it has two properties: Name and Subjects.

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

I created two instances of Student class, for example:

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);

Then I create a List studentList:

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

My question is, is there any way I can databind this studentList with a DataGridView, something like the following:

dataGridView.DataSource = studentList;

The first column is the student name and the second column is a combobox which shows all the subjects for the student.

Thank you for your time in advance.


回答1:


Something like this will work:

  1. Add a RowDataBound event to your grid and create a template column to hold the dropdownlist for the subjects:

    <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. Then on code behind handle the RowDataBound event as so:

    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();
      }
    }
    

Renders:

BTW, your Student class should look like this:

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;
     }
}


来源:https://stackoverflow.com/questions/14266457/datagridview-databinding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!