Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 458
Microsoft DN Avatar asked Jul 14 '15 10:07

Microsoft DN


People also ask

How do you reference a column in a DataFrame by index?

Use DataFrame. loc[] and DataFrame. iloc[] to select a single column or multiple columns from pandas DataFrame by column names/label or index position respectively. where loc[] is used with column labels/names and iloc[] is used with column index/position.


1 Answers

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);
like image 105
Fabjan Avatar answered Sep 25 '22 13:09

Fabjan