Sub GridView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs)
Dim Row As GridViewRow
Dim SelectedValue As String = ViewState("SelectedValue")
If SelectedValue Is Nothing Then
Return
End If
' 檢測選擇的行是哪個並重新選中它
For Each Row In GridView1.Rows
Dim KeyValue As String = GridView1.DataKeys(Row.RowIndex).Value
If (KeyValue = SelectedValue) Then
GridView1.SelectedIndex = Row.RowIndex
End If
Next
End Sub
Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
' 儲存選中行的索引
If (Not GridView1.SelectedIndex = -1) Then
ViewState("SelectedValue") = GridView1.SelectedValue
End If
End Sub
Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs)
' 重設選中索引
GridView1.SelectedIndex = -1
End Sub
Sub GridView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs)
' 重設選擇索引
GridView1.SelectedIndex = -1
End Sub
GridView和DetailsView還支援一種用於分頁和排序的特殊模式,它利用用戶端向伺服器的回調(callback)操作來擷取新頁面的資料或最近排序過的資料。要啟用這個特性,必須把EnableSortingAndPagingCallbacks屬性設定為真。請注意,當我們執行分頁或排序操作的時候,頁面不需要發回(postback)以檢索新值(儘管執行了用戶端指令碼向伺服器的回調操作)。當GridView或DetailsView包含模板欄位的時候是不支援這個特性的。當這個特性被啟用的時候,不支援在CommandField(命令欄位)中顯示"選擇"按鈕。