填充 DataSet
后,我将两个 DataGridViewComboBoxColumns
插入到某个特定的索引中:
dgvPayments.Columns.Insert(1, cmbPayMethod);
dgvPayments.Columns.Insert(3, cmbPayType);
dgvPayments.Columns.Insert(5, cmbMonth);
我在此 DataGridView
中有一个单元格点击事件,我在其中检查索引:
if (e.ColumnIndex == 6)
{
...
}
我第一次加载数据时,列索引命中了正确的列,但在清除数据后,列索引没有命中。怎么了?
最佳答案
如果您的设置是这样的:
- 在表单构造函数中,将
DataGridView.DataSource
绑定(bind)到一个集合。 - 在
Form.Load
中,插入您在 OP 中显示的列。 “清除数据”包括重新绑定(bind)
DataSource
。this.dataGridView.DataSource = emptyDataSource;
然后重新绑定(bind) DataSource
实质上删除了源列并重新添加它们。这会将手动插入的列的索引重新调整为第一个 - 但是它会保持 DisplayIndex
不变。
例如:
// DataSource added.
╔══════════════╦════════════╦════════════╦════════════╗
║ ║ "Source 1" ║ "Source 2" ║ "Source 3" ║
╠══════════════╬════════════╬════════════╬════════════╣
║ Index ║ 0 ║ 1 ║ 2 ║
║ DisplayIndex ║ 0 ║ 1 ║ 2 ║
╚══════════════╩════════════╩════════════╩════════════╝
// Column inserted at index 1.
╔══════════════╦════════════╦════════════╦════════════╦════════════╗
║ ║ "Source 1" ║ "Insert 1" ║ "Source 2" ║ "Source 3" ║
╠══════════════╬════════════╬════════════╬════════════╬════════════╣
║ Index ║ 0 ║ 1 ║ 2 ║ 3 ║
║ DisplayIndex ║ 0 ║ 1 ║ 2 ║ 3 ║
╚══════════════╩════════════╩════════════╩════════════╩════════════╝
// DataSource rebound.
╔══════════════╦════════════╦════════════╦════════════╦════════════╗
║ ║ "Source 1" ║ "Insert 1" ║ "Source 2" ║ "Source 3" ║
╠══════════════╬════════════╬════════════╬════════════╬════════════╣
║ Index ║ 1 ║ 0 ║ 2 ║ 3 ║
║ DisplayIndex ║ 0 ║ 1 ║ 2 ║ 3 ║
╚══════════════╩════════════╩════════════╩════════════╩════════════╝
解决方案:
您之前检查索引的位置:
if (e.ColumnIndex == 1) // ==6 in your OP.
你可以改为:
检查该列的
DisplayIndex
:if (this.dataGridView.Columns[e.ColumnIndex].DisplayIndex == 1)
或者,更可取的是,检查该列的
名称
:if (this.dataGridView.Columns[e.ColumnIndex].Name == "Insert 1")
检查 Name
更可靠,因为它比 DisplayIndex
更改的可能性更小,并且对于 future 的开发人员而言更易于维护。
关于c# - DataGridViewColumn 索引在数据清除后发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43600772/