获取DatagridviewComboBoxCell的SelectedIndex
我有一个Winforms
应用程序,它有一个DataGridView
。 DataGridView
未绑定到数据源。 我正在读取一个文本文件,根据文件中的每一行,我将每行的值放在datagrid中。
我的网格中有一个ComboBoxColumn
。 它有一系列的项目。
我的目标是将单元格中显示的项目的索引保存到文件中。 但是,似乎ComboBoxCell
没有像ComboBox
那样的SelectedIndex
属性。
重要的是要提到我需要知道只有当用户点击“保存”选项时显示的项目的索引,所以我不相信editingControlShowing事件是我的方式去。
好吧,你得到它几乎正确:为了找到所选索引你需要编码EditingControlShowing
事件,只需确保保持对编辑期间使用的ComboBox
的引用:
// 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
事件。 Cells的Tag
是明显的存储位置:
void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { if (combo != null) dataGridView1[e.ColumnIndex, e.RowIndex].Tag = combo.SelectedIndex; }
在这个版本中,您显然会从Tag
检索索引,而不是从组合中检索索引。
当然你也可以从Value
找到一个Item
,如下所示:
DataGridViewComboBoxCell dcc = (DataGridViewComboBoxCell)dataGridView1[yourColumn, yourRow]; int index = dcc.Items.IndexOf(dcc.Value);
但这只会得到第一个拟合指数,而不是实际选择的指数。
上述就是C#学习教程:获取DatagridviewComboBoxCell的SelectedIndex分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1041803.html