3

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.

Leigh
  • 28,765
  • 10
  • 55
  • 103
user1709325
  • 41
  • 1
  • 2
  • Did you tried to bind the `studentList` with `dataGridView.DataSource = studentList`? then that's the one way to bind the `list` to `DataGridView`. what is your main problem here? – spajce Jan 10 '13 at 20:25

1 Answers1

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: enter image description here

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;
     }
}
Icarus
  • 63,293
  • 14
  • 100
  • 115