Get DatagridviewComboBoxCell's SelectedIndex

北战南征 提交于 2019-12-19 02:54:17

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/30157239/get-datagridviewcomboboxcells-selectedindex

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