Mas Bagol
Mas Bagol

Reputation: 4617

How to bind a list which is a property of an object to DataGridView?

I have two object. One of them has a property which is a list of other object. For example, I have an object Klass that has students property that contains a list of Student objects. I need my DataGridView to display data of students of the selected Klass object which is selected via a ComboBox. So, whenever I change the selected Klass with ComboBox, the data DataGridView will display a list of students according to the selected Klass object.

The simplified code written like this:

Student class:

public class Student
{
    public string name { get; set; }
    public string address { get; set; }
}

Klass class:

public class Klass
{
    public string name { get; set; }
    public BindingList<Student> students { get; set; }
}

Is there anyway to do that?

Upvotes: 0

Views: 271

Answers (2)

John
John

Reputation: 3702

Set the combobox displaymember:

        public Form1()
        {
            InitializeComponent();

            comboBox1.DisplayMember = "name";
            comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
        }

Fill the combobox with Klasselements:

        private void Form1_Load(object sender, EventArgs e)
        {
            BindingList<Klass> klassList = new BindingList<Klass>(Util.CreateMockupData());
            comboBox1.DataSource = klassList;
        }

Implement handler to the combobox to set the datasource of the datagridview:

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selectedKlass = comboBox1.SelectedItem as Klass;
            if (selectedKlass != null)
            {
                dataGridView1.DataSource = selectedKlass.students;
            }
        }

Upvotes: 1

Dev_FullStack
Dev_FullStack

Reputation: 33

You can do this in the code behind. Compare the selected item text with the keyword for loading students of the selected class and call the Load_Grid() method.

    if(cbexample.Text=="Klass1")
{
        Public Load_Grid()
        {
           //code to access the data from DB
        }
}

and so on.

Hope you find this useful.

Upvotes: 0

Related Questions