Well, you got it almost right: In order to find the chosen index you do need to code the EditingControlShowing
event, just make sure to keep a reference to the ComboBox
that is used during the edit:
// hook up the event somwhere:
dataGridView1.EditingControlShowing += dataGridView1_EditingControlShowing;
// keep a reference to the editing comtrol:
ComboBox combo = null;
// fill the reference, once it is valid:
void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
combo = e.Control as ComboBox;
}
Now you can use it:
private void Save_Click(object sender, EventArgs e)
{
int index = -1;
if (combo != null) index = combo.SelectedIndex;
// now do what you want..
}
Note that this is just a minimal example. If your users will edit several columns and rows before they press the 'Save' Buton, you will need to store either the ComboBoxes
, or, less expensive, the SelectedIndex
, maybe in the CellEndEdit
event on a per Cell basis. The Cells' Tag
are obvious storage places:
void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (combo != null)
dataGridView1[e.ColumnIndex, e.RowIndex].Tag = combo.SelectedIndex;
}
In this version you will obviously retrieve the index from the Tag
, not from combo..
Of course you could also find an Item
from the Value
like this:
DataGridViewComboBoxCell dcc =
(DataGridViewComboBoxCell)dataGridView1[yourColumn, yourRow];
int index = dcc.Items.IndexOf(dcc.Value);
But that will simply get the first fitting index, not the one that was actually chosen..