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)<br /> {<br /> TableCell Cell;<br /> for (int Index = 0; Index < aGridView.HeaderRow.Cells.Count; Index++)<br /> {<br /> Cell = aGridView.HeaderRow.Cells[Index];<br /> if (Cell.Text.ToString() == ColumnText)<br /> return Index;<br /> }<br /> return -1;<br /> }
VB.NET
Public Shared Function GetColumnIndexByHeaderText(ByVal aGridView As GridView, ByVal ColumnText As String) As Integer<br /> Dim Cell As TableCell<br /> For Index As Integer = 0 To aGridView.HeaderRow.Cells.Count - 1<br /> Cell = aGridView.HeaderRow.Cells(Index)<br /> If Cell.Text.ToString() = ColumnText Then<br /> Return Index<br /> End If<br /> Next Index<br /> Return -1<br /> 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)<br /> {<br /> System.Web.UI.WebControls.BoundField DataColumn;<br /> for (int Index = 0; Index < aGridView.Columns.Count; Index++)<br /> {<br /> DataColumn = aGridView.Columns[Index] as System.Web.UI.WebControls.BoundField;<br /> if (DataColumn != null)<br /> {<br /> if (DataColumn.DataField == ColumnText)<br /> return Index;<br /> }<br /> }<br /> return -1;<br /> }<br />
VB.NET
Public Shared Function GetColumnIndexByDBName(ByVal aGridView As GridView, ByVal ColumnText As String) As Integer<br /> Dim DataColumn As System.Web.UI.WebControls.BoundField<br /> For Index As Integer = 0 To aGridView.Columns.Count - 1<br /> DataColumn = TryCast(aGridView.Columns(Index), System.Web.UI.WebControls.BoundField)<br /> If Not DataColumn Is Nothing Then<br /> If DataColumn.DataField = ColumnText Then<br /> Return Index<br /> End If<br /> End If<br /> Next Index<br /> Return -1<br /> End Function<br />
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.
The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.