Microsoft DN
Microsoft DN

Reputation: 10010

how to get column Index by column name?

I have a datagrid having few columns-

The header of the grid is hyperlink and I am setting its value at runtime as follows-

string strQ1 = "<a href='somePage.aspx?ID=1'>gfgytyty<a>";
dtGrid.Columns[0].Header = strq1;

string strQ2 = "<a href='somePage.aspx?ID=2'>yhtryrtuyu<a>";
dtGrid.Columns[1].Header = strq2;

and so on...

It is working properly. Now suppose I want to get index of a perticular column of datatgrid by its name but I am not able to get it. I tried

int  colIndex = dtGrid.Columns.IndexOf(dtGrid.Columns[strQ2]);

this should return 1 as columnIndex but it is returning -1,

Also, dtGrid.Columns[strQ2] giving me the null value.

what I am doing wrong here?

Upvotes: 5

Views: 21850

Answers (2)

Fabjan
Fabjan

Reputation: 13676

You could use LINQ FirstOrDefault to get the object first and only then use .IndexOf(object) :

var targetColumn = dtGrid.Columns.FirstOrDefault(c => c.Header == strQ2);
var index = dtGrid.Columns.IndexOf(targetColumn);

Upvotes: 10

Tim Schmelter
Tim Schmelter

Reputation: 460018

Here's another approach using List.FindIndex:

int index = dtGrid.Columns.ToList().FindIndex(c => c.Header  == strQ2);

If it's not the WPF DataGrid(which it seems to be due to the Header property) but a winforms DataGridView that doesn't implement a generic collection type, you need to cast it before you can use LINQ methods:

var columnList = dtGrid.Columns.Cast<DataGridViewColumn>().ToList();
int index = columnList.FindIndex(c => c.HeaderText  == strQ2);

Upvotes: 8

Related Questions