【问题标题】:DataGridViewColumn index gets changed after data clearing数据清除后 DataGridViewColumn 索引被更改
【发布时间】:2017-09-21 21:12:25
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: c# indexing datagridview display


    【解决方案1】:

    如果您的设置是这样的:

    1. 在表单构造函数中,将DataGridView.DataSource 绑定到一个集合。
    2. Form.Load 中,插入您在 OP 中显示的列。
    3. “清除数据”包括重新绑定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 更改的可能性更小,并且更便于未来的开发人员维护。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      • 2018-07-17
      • 2021-01-13
      • 1970-01-01
      • 2021-05-08
      • 2018-08-08
      • 1970-01-01
      相关资源
      最近更新 更多