[ACCEPTED]-How to reference column name instead of e.ColumnIndex in WinForm DataGridView event handlers?-datagridview
Accepted answer
Sure. It's of course not directly in the DataGridViewCellEventArgs
, but 1 it's easily obtainable. In your event handler:
DataGridView dgv = (DataGridView)sender;
string columnName = dgv.Columns[e.ColumnIndex].Name;
if (e.ColumnIndex == dgv.Columns["CustomerName"].Index )
{
and so on....
}
0
The answers above works great but if you 5 have to reference cell index a lot then 4 I will just add private int members to the 3 form, name them "idxMeaningfulColumnNameHere", then 2 initialize these members in Form's constructor. I 1 found it much easier this way.
idxMeaningfulColumnNameHere =
this.YourDataGridViewNameHere.Columns["ColumnNameHere"].Index
Here is a custom method to be added to your 1 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()
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.