views:

780

answers:

2

Some event handlers for the WinForm DataGridView have DataGridViewCellEventArgs as a parameter and a ColumnIndex as a property of that argument.

ColumnIndex is a number representing the column's ordinal #.

Is there a way to reference a column name from that argument instead of column index?

So instead of doing:

if (e.ColumnIndex == 1)

I prefer something like:

if (e.ColumnName == "CustomerName")

because if a column changes its position, it will break the code.

+1  A: 

Sure. It's of course not directly in the DataGridViewCellEventArgs, but it's easily obtainable. In your event handler:

DataGridView dgv = (DataGridView)sender;
string columnName = dgv.Columns[e.ColumnIndex].Name;
lc
A: 

if (e.ColumnIndex == dgv.Columns["CustomerName"].Index ) { and so on....
}

Crowcoder