Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference column name instead of e.ColumnIndex in WinForm DataGridView event handlers?

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.

like image 390
Tony_Henrich Avatar asked Jul 15 '09 16:07

Tony_Henrich


2 Answers

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;
like image 57
lc. Avatar answered Sep 23 '22 20:09

lc.


if (e.ColumnIndex == dgv.Columns["CustomerName"].Index )
{
    and so on....            
}
like image 33
Crowcoder Avatar answered Sep 21 '22 20:09

Crowcoder