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

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

ColumnIndex is a number indicating the ordinal number of column #.

Is there a way to refer to the column name from this argument instead of the column index?

So instead:

 if (e.ColumnIndex == 1) 

I prefer something like:

 if (e.ColumnName == "CustomerName") 

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

+6
winforms datagridview
source share
4 answers

Of course. This, of course, is not directly in the DataGridViewCellEventArgs , but it is easily obtained. In the event handler:

 DataGridView dgv = (DataGridView)sender; string columnName = dgv.Columns[e.ColumnIndex].Name; 
+8
source share
 if (e.ColumnIndex == dgv.Columns["CustomerName"].Index ) { and so on.... } 
+5
source share

The answers above work fine, but if you need to reference the cell index multiple times, I just add private int members to the form, name them "idxMeaningfulColumnNameHere", and then initialize these elements in the form constructor. I found this a lot easier.

 idxMeaningfulColumnNameHere = this.YourDataGridViewNameHere.Columns["ColumnNameHere"].Index 
+3
source share

Here is a special method that will 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 this, you can do something like:

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

All Articles