I have run into this issue too. Although I found a few posts that really don't work when you use paging, I created the class below to search and return the page and grid index: (You will need to supply it with your GridView, the Primary Key, the datatable, and any filter parameters)
Hope this helps.
I appreciate any feedback to make it better.
'*****Search a gridview for a key and return the PageIndex and SelectedIndex (GridIndex)
'Supply the GridView, Key Field Value, Underlying Data Table, and any filter string
'
'e.g.
'Protected Sub DetailsView1_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles DetailsView1.ItemInserted
' Dim mEquipBll As New EquipBLL
' Dim mGridFind As New GridFind(GridView1, e.Values("myKey"), getDataTable(), "Whatever = 'Whatever'")
' GridView1.PageIndex = mGridFind.PageIndex
' GridView1.SelectedIndex = mGridFind.GridIndex
'End Sub
Imports Microsoft.VisualBasic
Imports System.Data
Public Class GridFind
Protected _GridView As GridView
Protected _GridKey As Integer
Protected _DataTable As Data.DataTable
Protected _FilterString As String
Protected _PageIndex As Integer
Protected _GridIndex As Integer
Public ReadOnly Property PageIndex() As Integer
Get
Return _PageIndex
End Get
End Property
Public ReadOnly Property GridIndex() As Integer
Get
Return _GridIndex
End Get
End Property
Public Sub New(ByVal fGridView As GridView, ByVal fGridKey As Integer, ByVal fDataTable As DataTable, ByVal fFilterString As String)
_GridView = fGridView
_GridKey = fGridKey
_DataTable = fDataTable
_FilterString = fFilterString
Dim NewTable As DataTable = getNewTable()
Dim SelectRow As Data.DataRow = NewTable.Rows.Find(_GridKey)
Dim DataIndex As Integer = NewTable.Rows.IndexOf(SelectRow)
_PageIndex =
Fix(DataIndex / _GridView.PageSize)
_GridIndex =
DataIndex Mod _GridView.PageSize
End Sub
Private Function getNewTable() As DataTable
Dim mDataView As DataView = _DataTable.DefaultView
Dim dv As Data.DataView = _DataTable.DefaultView
If _GridView.SortExpression <> "" Then
dv.Sort = _GridView.SortExpression
Select Case _GridView.SortDirection
Case SortDirection.Ascending
dv.Sort += " ASC"
Case SortDirection.Descending
dv.Sort += " DESC"
End Select
End If
dv.RowFilter = _FilterString
Dim newDt As DataTable
newDt = dv.ToTable()
newDt.PrimaryKey = New Data.DataColumn() {newDt.Columns(_GridView.DataKeyNames(0))}
Return newDt
End Function
End Class