0
votes

I have a DataGridView in winforms, that contains a combobox column. The gridview is filled programmatically, and it is empty at start. "list" is a list containing custom objects. Value1/2/3 are unique to each row.

int[] array = new[] {value1,value2,value3}
for (int i = 0; i < list.Count; i++)
{
    DataRow newrow = MyDataTable.NewRow();
    newrow["idColumn"] = list[i].Customer_id;
    newrow["dateoforderColumn"] = list[i].Customer_date;
    newrow["commColumn"] = list[i].Customer_comment;
    // This is what I want, and can't get to work.
    newrow["comboColumn"] = array;
    // I have also tried (newrow["comboColumn"] as DataGridViewComboColumn).DataSource
    // but it didn't work either.

    MyDataTable.Rows.Add(newrow);
}

How can I populate a freshly created combobox cell? Also, I need to do it within the for loop, because I need the index to get the data.

1
Post how you add columns and how do you set DataSource - Sriram Sakthivel
Columns are added in the designer, and its only datasource is that datatable, which is created programmatically. - zergerge

1 Answers

1
votes

From the look of your code you just have one array of values that you need to set. In this case you only need to set it once for the column, not for every row, i usually do this in the constructor or before populating rows.

        //Clear any junk items that may have been there from the designer or previous view
        ((DataGridViewComboBoxColumn)MyDataTable.Columns["comboColumn"]).Items.Clear();
        //Add you new values
        ((DataGridViewComboBoxColumn)MyDataTable.Columns["comboColumn"]).Items.AddRange(array);

Then to set the value of the new row's cell

        //Set value to be selected in new row
        newrow["comboColumn"] = list[i].Customer_value;