Search code examples
datagridviewdatagridcomboboxcolumn

Populating Combobox column in Datagridview from data source


I need your help regarding C# datagridview. I want to generate a datagridview from a datasource. The data grid view has 4 column. Column1: firstname Column2: Last name Column3: gender Column4: Country. Country column is a combobox column.

I have created the datasource accordingly and set the data source to the grid. First three column is generating but the Combo box is not getting added. Here is the example code of my app

List<Mydataclass> dataclassList = new List<Mydataclass>();
for (int i = 0; i < 5; i++)
        {
            Mydataclass dataclass = new Mydataclass();
            dataclass.firstname = "firstname" + i;
            dataclass.secondname = "second name" + i;
            dataclass.gender = "gender" + i;
            dataclass.country = new string[] { "BD", "AUS"};

            dataclassList.Add(dataclass);

        }
BindingSource bindingSource1 = new BindingSource();

        bindingSource1.DataSource = dataclassList;
        dataGridView1.DataSource = bindingSource1;

When I run the app, the datagrid is showing up with 3 column but the combo box column is not generating.

Please help me to find the issue.

Thanks in advance.


Solution

  • This is what works for me:

    // This is the list of items to be displayed in the DataGridView Combobox Column
    string[] listOfItems = new string[]{"Apple", "Banana", "Orange"};
    
    // Define a BindingSource and add the items to it (alas, there is no AddRange())
    BindingSource bs = new BindingSource();
    
    foreach (string item in listOfItems)
    {
        bs.Add(item);
    }
    
    // Set binding (MyComboColumn is the name you gave to your combo column, see image below)
    this.MyComboColumn.DataSource = bs;
    

    enter image description here