Hi damu maddy,
ComboBoxCell doesn't support SelectedIndex property, I have found two way to achieve.
1. Set the initial value of the ComboBoxCell.
For example, here is a table with CountryID and CountryName
private DataTable dtCountry = new DataTable();
dtCountry.Columns.Add("CountryID", typeof(int));
dtCountry.Columns.Add("CountryName", typeof(string));
dtCountry.Rows.Add(1, "Canada");
dtCountry.Rows.Add(2, "USA");
dtCountry.Rows.Add(3, "Mexico");
I will create a new DataGridViewComboBoxCell instance and set its initial value with the first row in dtCountry.
DataGridViewComboBoxCell dgvCmbCell = new DataGridViewComboBoxCell();
dgvCmbCell.DataSource = dtCountry;
dgvCmbCell.DisplayMember = "CountryName";
dgvCmbCell.ValueMember = "CountryID";
// use this cell on row[0] cell[1]
dataGridView1.Rows[0].Cells[1] = dgvCmbCell;
if (dataGridView1.Rows[0].Cells[1].Value.ToString() == "")
{
dgvCmbCell.Value = dtCountry.Rows[0]["CountryID"];
}
2. Set the SelectedIndex to 0 when you click the cell and want to edit it. So you need to handleEditingControlShowing event.
dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);
void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox cmb = e.Control as ComboBox;
if (cmb != null)
{
cmb.SelectedIndex = 0;
}
}
Holp this can help you!
If you have any question, please tell me.
Sincerely,
Kira Qian
Please mark the replies as answers if they help and unmark if they don't.