I have a Winforms
application which has a DataGridView
.
The DataGridView
is not bound to a datasource. I'm reading a text file and according to each line in the file, I'm placing the values of each row to the datagrid.
I have a column in my grid that is a ComboBoxColumn
. It has a collection of items in it.
My goal is to save to the file the index of the item that is displayed in the cell.
However, it seems that ComboBoxCell
doesn't have the SelectedIndex
property like ComboBox
.
It is important to mention that I need to know the index of the item displayed only when the user hits "Save" option, So I don't believe that editingControlShowing event is my way to go.
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With