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

标签 c# indexing datagridview display

填充 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 绑定(bind)到一个集合。
  2. Form.Load 中,插入您在 OP 中显示的列。
  3. “清除数据”包括重新绑定(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/

相关文章:

c# - Entity Framework 代码优先 : CASCADE DELETE for same table many-to-many relationship

c# - 反向 Convert.ToBase64String(byte[] 数组)

c - 数据库系统中的文件组织和操作

C# - DataGridView 在 Cell 中换行文本但没有空格

c# - 扩展 NHibernate DriverConnectionProvider 类

oracle - oracle 索引的 last_analysed 日期是什么意思?

c++ - 使用 const 成员变量索引数组

c# - 从查找表中获取特定值?

c# - 将列表绑定(bind)到 gridview C#

c# - LINQ 语句作为 if 条件