获取DatagridviewComboBoxCell的SelectedIndex [英] Get DatagridviewComboBoxCell's SelectedIndex
问题描述
我有一个 Winforms
应用程序,它有一个 DataGridView
。
DataGridView
未绑定到数据源。我正在读取一个文本文件,并根据文件中的每一行,我将每行的值放在datagrid。
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.
我在我的一列网格是 ComboBoxColumn
。它有一个项目的集合。
I have a column in my grid that is a ComboBoxColumn
. It has a collection of items in it.
我的目标是将文件中的项目的索引保存到文件中。
但是,似乎 ComboBoxCell
没有 SelectedIndex
属性,如 ComboBox
。
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
.
请注意,只有当用户点击保存选项时,才需要知道项目的索引,所以我不相信editControlShowing事件是我的方式。
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.
推荐答案
嗯,你几乎是正确的:按顺序要找到选择的索引,您 需要编写 EditingControlShowing
事件,请务必保留对 ComboBox
在编辑过程中使用:
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;
}
现在可以使用它:
private void Save_Click(object sender, EventArgs e)
{
int index = -1;
if (combo != null) index = combo.SelectedIndex;
// now do what you want..
}
注意,这只是一个最小的例子。如果您的用户在按保存按钮之前将编辑多个列和行,则需要存储 ComboBoxes
,或者较便宜的是 SelectedIndex
,也许在每个Cell的 CellEndEdit
事件中。单元格的标签
是明显的存储位置:
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;
}
在此版本中,您将显然会从标签
,而不是从combo ..
In this version you will obviously retrieve the index form 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..
这篇关于获取DatagridviewComboBoxCell的SelectedIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!