Method to Find GridView Column Index by Name

Viewed 71679

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.

7 Answers

Here's a VB version

Protected Function GetColumnIndexByHeaderText(grid As GridView, findHeader As String) As Integer
    Dim i As Integer = 0
    For i = 0 To grid.Columns.Count - 1
        If grid.Columns(i).HeaderText.ToLower().Trim() = findHeader.ToLower().Trim() Then
            Return i
        End If
    Next

    Return -1
End Function
Related