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.
Something like this will work:
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>
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With