30

I want to find column name in DataGridView. I have column index. How can I find it.

dGVTransGrid.CurrentCell.ColumnIndex: I want it's column name.

Plz help.

Thanks.

Beetee
  • 475
  • 1
  • 7
  • 18
Nagendra Kumar
  • 634
  • 2
  • 12
  • 20

7 Answers7

50

There may be a better way, but why don't you just ask the DataGridView what the column with that index is called?

int columnIndex = dGVTransGrid.CurrentCell.ColumnIndex;
string columnName = dGVTransGrid.Columns[columnIndex].Name;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
17

Found an easier way, on a single line.

[datagrid].CurrentCell.OwningColumn.Name

hope it helps.

br, Eric Estrada Gomez

3

If you want it dynamic on the cell clicked then you can get it from the event

private void dataGridViewName_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    String columnName = this.dataGridViewName.Columns[e.ColumnIndex].Name;

}
CR41G14
  • 5,464
  • 5
  • 43
  • 64
1
for (var i = 0; i < DataGridView.ColumnCount; i++)
var name = DataGridView.Columns[i].HeaderText;

this is a simple way of doing it.

Gabriel Marius Popescu
  • 2,016
  • 2
  • 20
  • 22
1

In a single row of code

String name = dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name;
daniele3004
  • 13,072
  • 12
  • 67
  • 75
0

I think I'm quite late to answer this, I was going through the same requirement and I found this query. I tried the below code snippet and it worked for me:

Since you said you know index, you can use the below snippet. If you already have an index number, then you can directly fetch the column name based on that index.

Dim index As Integer = 0 
Dim grid As DataGridView
Dim colName As String = grid.ColumnFields(index).HeaderText

If you don't know the index number, you can use the below snippet.

Dim colIndex As Integer = 0
Dim colName As String = "" 
Dim grid As DataGridView
For index As Integer = 0 To grid.ColumnFields.Length - 1
    If grid.ColumnFields(index).HeaderText = colName Then
        colIndex = index
        Exit For
    End If
Next
Javid
  • 1
  • 1
-1

It may be helps you:

String s = dataGridView1.Columns[Index].HeaderText;
  • 2
    This is not correct - column Names and Header Text do not have to be the same. – Ken Oct 17 '16 at 04:01