Method to Find GridView Column Index by Name

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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

Method 3

Better solution which works for Datafield, SortExpression and headerText.

public static int GetBoundFieldIndexByName(this GridView gv,string name)
    {
        int index = 0;
        bool found = false;
        foreach (DataControlField c in gv.Columns)
        {
            if (c is BoundField)
            {
                BoundField field = (BoundField)c;
                if (name == field.DataField ||
                    name == field.SortExpression ||
                    name == field.HeaderText)
                {
                    found = true;
                    break;
                }
            }
            index++;
        }
        return found ? index : -1;
    }

Method 4

//Get index of column by header text.
    int GetColumnIndexByName(GridViewRow row, string headerText)
    {
        int columnIndex = 0;
        foreach (DataControlFieldCell cell in row.Cells)
        {
            if(cell.ContainingField is TemplateField){
                if(((TemplateField)cell.ContainingField).HeaderText.Equals(headerText))
                {
                    break;
                } 
            }
          if(cell.ContainingField is BoundField){
                    if (((BoundField)cell.ContainingField).HeaderText.Equals(headerText))
                {
                    break;
                }
          }
            columnIndex++; 
        }


        return columnIndex;
    }

Method 5

In case if you need a column itself and not just its index you can use some Linq magic:

DataControlField col=GridView1.Columns.Cast<DataControlField>().First(c => c.HeaderText == "Column_header")

Method 6

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

Method 7

This way, works for me (.NET Gridview):

    private int GetColumnIndexByName(GridView grid, string name)
    {
        for (int i = 0; i < grid.HeaderRow.Cells.Count; i++)
        {
            if (grid.HeaderRow.Cells[i].Text.ToLower().Trim() == name.ToLower().Trim())
            {
                return i;
            }
        }
        return -1;
    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x