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?
If your setup is thus:
DataGridView.DataSource to a collection.Form.Load, insert columns as you've shown in the OP."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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With