Since the code does not show how the columns are constructed, it is difficult to tell what the problem could be, however the code is not using the DataGridViewComboBoxColum
. The DataGridViewComboBoxColumn
is all you need to make every row in column 0 a combo box with “Male”, “Female” choices.
The malformed foreach
loop is incorrect and will not compile. I assume a for
loop is what you were looking for. Following this for
loop… a new row is correctly added to the grid. Then a new DataGridViewComboBoxCell
is created and added the cell[0] of the current row. dataGridView1.Rows[counter].Cells[0] = cbCell;
. This cell[0] is added to every new row.
This is unnecessary if the DataGridViewViewComboBoxColumn
is set up properly. Adding the DataGridViewComboBoxCell
is perfectly valid and basically allows you to put a combo box into any “SINGLE” cell. It works however, if used this way makes the use of the combo box itself questionable.
The loop is “adding” data to dataGridView1
. As you are reading in the data, the part about “Gender” (male, female) appears to be missing so the value is not set as the other values are. Example: There is not a line like below:
dataGridView1.Rows[counter].Cells[0].Value = gender[counter];
If there was a “Gender” array that held this info, then when the code sets this value (Male, Female) in the line of code above the combo box column will automatically set the combo box selection to that value. The data will only be “one” (1) of the two values.
So assuming this is what you are looking for the code below demonstrates how to use the DataGridViewComboBoxColumn
A word of caution when reading data into a combo box cell; if the string data for the combo box column does NOT match one of the items in the combo boxes items list, the code will crash if not caught and addressed. If the value is an empty string then the combo box will set the selected value to empty.
// Sample data
string[] firstname = { "John", "Bob", "Cindy", "Mary", "Clyde" };
string[] lastname = { "Melon", "Carter", "Lawrence", "Garp", "Johnson" };
string[] gender = { "Male", "", "Female", "", "Male" };
// Create the combo box column for the datagridview
DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
comboCol.Name = "Gender";
comboCol.HeaderText = "Gender";
comboCol.Items.Add("Male");
comboCol.Items.Add("Female");
// add the combo box column and other columns to the datagridview
dataGridView1.Columns.Add(comboCol);
dataGridView1.Columns.Add("FirstName", "First Name");
dataGridView1.Columns.Add("LastName", "Last Name");
// read in the sample data
for (int counter = 0; counter < 5; counter++ )
{
dataGridView1.Rows.Add(gender[counter], firstname[counter], lastname[counter]);
}
Hope this helps.