Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to Find GridView Column Index by Name

Tags:

I'm trying to write a small method to loop through and find a GridView Column by its Index, since it can change position based on what might be visible.

Here is what I have so far:

private int GetColumnIndexByName(GridView grid, string name)
{
    foreach (DataColumn col in grid.Columns)
    {
        if (col.ColumnName.ToLower().Trim() == name.ToLower().Trim()) return col.Ordinal;
    }

    return -1;
}

In this case, DataColumn doesn't appear to be the right type to use, but I'm kind of lost as to what I should be doing here.

I can only use .NET 2.0 / 3.5. I can't use 4.0.

like image 754
Delebrin Avatar asked Oct 13 '10 15:10

Delebrin


2 Answers

I figured it out, I needed to be using DataControlField and slightly different syntax.

The working version:

private int GetColumnIndexByName(GridView grid, string name)
    {
        foreach (DataControlField col in grid.Columns)
        {
            if (col.HeaderText.ToLower().Trim() == name.ToLower().Trim())
            {
                return grid.Columns.IndexOf(col);
            }
        }

        return -1;
    }
like image 146
Delebrin Avatar answered Sep 28 '22 06:09

Delebrin


I prefer collection iteration but why bother with the overhead of foreach and grid.Columns.IndexOf call in this case? Just iterate through array with an index.

private int GetColumnIndexByName(GridView grid, string name)
{
    for(int i = 0; i < grid.Columns.Count; i++)
    {
        if (grid.Columns[i].HeaderText.ToLower().Trim() == name.ToLower().Trim())
        {
            return i;
        }
    }

    return -1;
}
like image 30
David Sopko Avatar answered Sep 28 '22 04:09

David Sopko