How do I get the index of a column by the column name?
I have a datagrid with multiple columns -
The grid title is a hyperlink and I set its value at runtime like this:
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 works correctly. Now, suppose I want to get the index of the datatgrid columnar column by its name, but I cannot get it. I tried
int colIndex = dtGrid.Columns.IndexOf(dtGrid.Columns[strQ2]);
this should return 1 as columnIndex, but it returns -1,
Also dtGrid.Columns [strQ2] gives me a null value.
what am i doing wrong here?
source to share
Here's a different approach using List.FindIndex
:
int index = dtGrid.Columns.ToList().FindIndex(c => c.Header == strQ2);
If it is not WPF DataGrid
(which appears to be property bound Header
) but winforms DataGridView
which does not implement a generic collection type, then you need to discard it before you can use LINQ methods:
var columnList = dtGrid.Columns.Cast<DataGridViewColumn>().ToList();
int index = columnList.FindIndex(c => c.HeaderText == strQ2);
source to share