Method to Find GridView Column Index by Name
<p>I am 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. I'm not sure if I'm taking the right approach and I can't quite get it working. Can anyone lend a hand?</p>

<p>Here is what I have so far: </p>

<pre><code>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;
}
</code></pre>

<p>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. Hopefully someone can give me some ideas where I'm going wrong.</p>

<p>I also need a solution for .NET 2.0 / 3.5. I can't use 4.0. Thanks for any help you can provide!</p>

<p>EDIT: I figured it out, I needed to be using DataControlField and slightly different syntax. </p>

<p>The working version: </p>

<pre><code>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;
    }
</code></pre>
