Get DatagridviewComboBoxCell's SelectedIndex

☆樱花仙子☆ 提交于 2019-11-30 20:26:59

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!