tkaragiris posted on February 15, 2010 15:07

The following function will return the index number of a column in a gridview or detailsview control based on it's header text. Just pass in the control and header text as parameters.
' Get field index by Header Text, works with both gridview and detailsview
Public Shared Function GetFieldIndexByHeader(ByVal _Control As Object, ByVal _HeaderText As String) As Integer
If _HeaderText <> "" Then
Dim _Field As DataControlField
Select Case _Control.GetType.ToString
Case "System.Web.UI.WebControls.DetailsView"
For Each _Field In _Control.Fields
If _Field.HeaderText.ToLower = _HeaderText.ToLower Then
Return _Control.Fields.IndexOf(_Field)
End If
Next
Case "System.Web.UI.WebControls.GridView"
For Each _Field In _Control.Columns
If _Field.HeaderText.ToLower = _HeaderText.ToLower Then
Return _Control.columns.IndexOf(_Field)
End If
Next
End Select
Else
Return -1
End If
End Function