7

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.

4 Answers 4

10

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; 
Sign up to request clarification or add additional context in comments.

1 Comment

string columnName = dgv.Columns(e.ColumnIndex).Name; if you are using VB.NET instead of C#
6
if (e.ColumnIndex == dgv.Columns["CustomerName"].Index ) { and so on.... } 

1 Comment

On my RadGridView I need the UniqueName="CustomerName" set
4

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 

Comments

0

Here is a custom method to be added to your DGV.

<Extension()> Friend Function getColumnIndexByName(ByRef dgv As DataGridView, ByRef colName As String) As Integer For Each column As DataGridViewColumn In dgv.Columns If column.Name = colName Then Return column.Index Next Try Throw New Exception("Column Name not Found") Catch ex As Exception MessageBox.Show(colName & ": " + ex.Message) End Try Return -1 End Function 

With that you can do something like:

If dgv1.getColumnIndexByName("SOME_COLUMN_NAME") = e.ColumnIndex Then Do_something() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.