Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridViewColumn index gets changed after data clearing

After filling DataSet, I insert two DataGridViewComboBoxColumns into some particular index:

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

I have a cell click event in this DataGridView where I check against the index:

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

The first time I load the data the column index hits the correct column, but after clearing data the column index does not. What is wrong?

like image 608
Hilal Al-Rajhi Avatar asked May 16 '26 06:05

Hilal Al-Rajhi


1 Answers

If your setup is thus:

  1. In the form constructor, bind the DataGridView.DataSource to a collection.
  2. In Form.Load, insert columns as you've shown in the OP.
  3. "Clearing data" includes re-binding the DataSource.

    this.dataGridView.DataSource = emptyDataSource;
    

Then re-binding the DataSource essentially removes the sourced columns and readds them. This readjusts the manually inserted columns' indices to be the first ones - however it leaves the DisplayIndex untouched.

For example:

// 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     ║
╚══════════════╩════════════╩════════════╩════════════╩════════════╝

Solution:

Where you previously check for the index:

if (e.ColumnIndex == 1) // ==6 in your OP.

You could instead:

  • Check that column's DisplayIndex:

    if (this.dataGridView.Columns[e.ColumnIndex].DisplayIndex == 1)
    
  • Or, more preferably, check that column's Name:

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

Checking the Name is more reliable as it is less likely to change than the DisplayIndex and is more maintainable for future developers.

like image 117
OhBeWise Avatar answered May 18 '26 18:05

OhBeWise