GridView Utilities in C# and VB.NET

 Rate It (1)

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

Revision number 3, Sunday, December 28, 2008 10:19:51 AM by SGWellens

Comments

good

its helpful

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. mbanavige (14)
  2. codehard (3)
  3. Babunareshnarra (2)
  4. Dungimon (1)
  5. cabhilash (1)
Microsoft Communities