65.9K
CodeProject is changing. Read more.
Home

GridView Utilities in C# and VB.NET

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Oct 11, 2013

CPOL
viewsIcon

7697

GridView UtilitiesThe GetColumnIndexByHeaderText method shown below finds the column index inside a GridView control by passing to it a GridView

GridView Utilities

The GetColumnIndexByHeaderText method shown below finds the column index inside a GridView control by passing to it a GridView instance together with the header text. If column is not found, a value of -1 is returned.

C#

    static public int GetColumnIndexByHeaderText(GridView aGridView, String ColumnText)
    {
        TableCell Cell;
        for (int Index = 0; Index < aGridView.HeaderRow.Cells.Count; Index++)
        {
            Cell = aGridView.HeaderRow.Cells[Index];
            if (Cell.Text.ToString() == ColumnText)
                return Index;
        }
        return -1;
    }

VB.NET

 Public Shared Function GetColumnIndexByHeaderText(ByVal aGridView As GridView, ByVal ColumnText As String) As Integer
  Dim Cell As TableCell
  For Index As Integer = 0 To aGridView.HeaderRow.Cells.Count - 1
   Cell = aGridView.HeaderRow.Cells(Index)
   If Cell.Text.ToString() = ColumnText Then
   Return Index
   End If
  Next Index
  Return -1
 End Function

 

The GetColumnIndexByDBName method returns the column index inside a GridView control by specifying the data bound column name in the database. The return value will be either the column index if found else a value of -1.

C#

    static public int GetColumnIndexByDBName(GridView aGridView, String ColumnText)
    {
        System.Web.UI.WebControls.BoundField DataColumn;
for (int Index = 0; Index < aGridView.Columns.Count; Index++)
        {
            DataColumn = aGridView.Columns[Index] as System.Web.UI.WebControls.BoundField;
            if (DataColumn != null)
            {
                if (DataColumn.DataField == ColumnText)
                    return Index;
            }
        }
        return -1;
    }

VB.NET

 Public Shared Function GetColumnIndexByDBName(ByVal aGridView As GridView, ByVal ColumnText As String) As Integer
  Dim DataColumn As System.Web.UI.WebControls.BoundField
  For Index As Integer = 0 To aGridView.Columns.Count - 1
   DataColumn = TryCast(aGridView.Columns(Index), System.Web.UI.WebControls.BoundField)
   If Not DataColumn Is Nothing Then
    If DataColumn.DataField = ColumnText Then
     Return Index
    End If
   End If
  Next Index
  Return -1
 End Function