GridView控制項中的"選擇"操作純粹是一個UI概念,它的SelectedIndex屬性與表格的可視資料行中的當前被選中的行的索引相對應。如果
你啟用了表格的分頁和排序功能,在執行分頁或排序操作之後,SelectedIndex的值仍然不會變化,因此在執行這些操作之後,一個新資料行被選中
了。在某些環境下,保留對指定資料行的選中更好,即使該行在表格的當前頁面中並不可視。下面的例子示範了如何在排序和分頁操作之後仍然保留當前選中的資料
行。
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 SubProtected 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(命令欄位)中顯示"選擇"按
鈕。
<asp:GridView AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="au_id" DataSourceID="SqlDataSource1" EnableSortingAndPagingCallbacks="True" ID="GridView1" runat="server"> …… </asp:GridView> |
儘管GridView、DetailsView和FormView為分頁器(pager)UI提供了預設的顯示方式,你仍然可以通過設定
PagerTemplate屬性來自訂分頁器的顯示。在這個模板中,你可以放置按鈕控制項,並把它的CommandName屬性設定為Page,把它的屬
性設定為First、Prev、Next、Last或<number>,其中<number>是特定頁面的索引值。下面的例子示範了GridView和
DetailsView控制項定義的PagerTemplate。
<PagerTemplate>
<asp:LinkButton
CommandName="Page" CommandArgument="First" ID="LinkButton1"
runat="server" Style="color: white"><<
First</asp:LinkButton>
<asp:LinkButton CommandName="Page"
CommandArgument="Prev" ID="LinkButton2" runat="server" Style="color:
white">< Prev</asp:LinkButton>
[Records <%=
GridView1.PageIndex * GridView1.PageSize %> - <%= GridView1.PageIndex *
GridView1.PageSize + GridView1.PageSize - 1 %>]
<asp:LinkButton
CommandName="Page" CommandArgument="Next" ID="LinkButton3"
runat="server" Style="color: white">Next ></asp:LinkButton>
<asp:LinkButton
CommandName="Page" CommandArgument="Last" ID="LinkButton4"
runat="server" Style="color: white">Last
>></asp:LinkButton>
</PagerTemplate>