Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DatagridviewComboBoxCell's SelectedIndex

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.

like image 350
subirshan Avatar asked May 10 '15 22:05

subirshan


1 Answers

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..

like image 139
TaW Avatar answered Nov 05 '22 23:11

TaW