简体   繁体   中英

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?

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);

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);

为什么不呢?

int index = myDataGridView.Columns["myColumn"].Index;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM