DataGridViewColumn 索引在数据清除后发生变化

DataGridViewColumn index gets changed after data clearing

填充 DataSet 后,我将两个 DataGridViewComboBoxColumns 插入到某个特定索引中:

dgvPayments.Columns.Insert(1, cmbPayMethod);
dgvPayments.Columns.Insert(3, cmbPayType);
dgvPayments.Columns.Insert(5, cmbMonth);

我在此 DataGridView 中有一个单元格点击事件,我在其中检查索引:

if (e.ColumnIndex == 6)
{
 ...
}

我第一次加载数据时,列索引命中了正确的列,但在清除数据后,列索引没有命中。怎么了?

如果您的设置是这样的:

  1. 在表单构造函数中,将 DataGridView.DataSource 绑定到一个集合。
  2. Form.Load 中,插入您在 OP 中显示的列。
  3. "Clearing data" 包括重新绑定 DataSource.

    this.dataGridView.DataSource = emptyDataSource;
    

然后重新绑定 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)
    
  • 或者,更优选地,检查该列的 Name:

    if (this.dataGridView.Columns[e.ColumnIndex].Name == "Insert 1")
    

检查 Name 更可靠,因为它比 DisplayIndex 更改的可能性更小,并且对未来的开发人员更易于维护。