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

21,937

Solution 1

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;

Solution 2

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

Solution 3

The answers above works great but if you have to reference cell index a lot then I will just add private int members to the form, name them "idxMeaningfulColumnNameHere", then initialize these members in Form's constructor. I found it much easier this way.

idxMeaningfulColumnNameHere =
    this.YourDataGridViewNameHere.Columns["ColumnNameHere"].Index
Share:
21,937
Tony_Henrich
Author by

Tony_Henrich

Updated on October 22, 2020

Comments

  • Tony_Henrich
    Tony_Henrich over 3 years

    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.

  • AdrienTorris
    AdrienTorris almost 8 years
    string columnName = dgv.Columns(e.ColumnIndex).Name; if you are using VB.NET instead of C#
  • Devid
    Devid about 7 years
    On my RadGridView I need the UniqueName="CustomerName" set