2017-04-25 59 views
2

填充DataSet後之後得到改變,我插入兩個DataGridViewComboBoxColumns到一些特定的索引:的DataGridViewColumn索引數據清除

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

我在這DataGridView,我覈對了索引的小區單擊事件:

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

我第一次加載數據的列索引擊中正確的列,但清除數據後,列索引沒有。哪裏不對?

回答

0

如果你的設置是這樣的:

  1. 在窗體構造函數中,綁定DataGridView.DataSource到集合。
  2. Form.Load中,按照您在OP中所示的方式插入列。
  3. 「清除數據」包括重新綁定DataSource

    this.dataGridView.DataSource = emptyDataSource; 
    

然後再結合DataSource實質上是刪除源列和readds他們。這將手動插入的列索引重新調整爲第一個索引 - 但它不會改變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,對未來的開發人員更具可維護性。