现在的位置: 首页 > 综合 > 正文

讓 GridView 的 CheckBoxField 產生 PostBack 並攔截事件

2013年05月10日 ⁄ 综合 ⁄ 共 2556字 ⁄ 字号 评论关闭
在上一篇「GridView 中的子控制項取得所屬的 GridViewRow 及 RowIndex
文章中有提到 TemplateField 中的 ChckBox 產生 PostBack 觸發事件,若我們希望直接使用 CheckBoxField 能不能達到相同 PostBack 的效果呢?以下的範例,就是要以 CheckBoxField 來達到相同效果。

假設要執行 PostBack 的 CheckBoxField 置於 GridView 中第二個欄位(欄位索引為1)。

 1         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"
 2             DataSourceID="SqlDataSource1" EmptyDataText="沒有資料錄可顯示。">
 3             <Columns>
 4                 <asp:CommandField ShowEditButton="True" />
 5                 <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" SortExpression="Discontinued" />
 6                 <asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" SortExpression="ProductID" />
 7                 <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
 8                 <asp:BoundField DataField="SupplierID" HeaderText="SupplierID" SortExpression="SupplierID" />
 9                 <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" SortExpression="CategoryID" />
10             </Columns>
11         </asp:GridView>

我們必須在 GridView 的 RowCreated 事件中,抓取 CheckBoxField 欄位中的 CheckBox 控制項,設定其
AutoPostBack 為 True,並攔截它的 CheckedChanged 事件導向 CheckBox1_CheckedChanged
函式。

 1 Partial Class _Default
 2     Inherits System.Web.UI.Page
 3 
 4     Protected Sub GridView1_RowCreated(ByVal sender As Object,ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
                
Handles GridView1.RowCreated
 5         Dim oCheckBox As CheckBox
 6         If e.Row.RowType = DataControlRowType.DataRow Then
 7             'CheckBoxField 的欄位索引為 1
 8             oCheckBox = CType(e.Row.Cells(1).Controls(0), CheckBox)
 9             oCheckBox.AutoPostBack = True
10             AddHandler oCheckBox.CheckedChanged, AddressOf CheckBox1_CheckedChanged
11         End If
12     End Sub
13 
14     Protected Sub CheckBox1_CheckedChanged(ByVal sender As ObjectByVal e As System.EventArgs)
15         Dim oCheckBox As CheckBox
16         Dim oGridViewRow As GridViewRow
17         Dim iRowIndex As Integer
18 
19         oCheckBox = CType(sender, CheckBox)
20 
21         '取得控制項所屬性 GridViewRow
22         oGridViewRow = CType(oCheckBox.BindingContainer, GridViewRow)
23 
24         '取得目前 GridViewRow 的索引
25         iRowIndex = oGridViewRow.RowIndex
26     End Sub
27 
28 End Class

執行程式後,你會發覺與上一篇文章有相同的效果。這種讓 GridView 欄位可引發 PostBack 的作法是適用其他如 BoundField、HyperLinkField ...等欄位。
不過注意一點,設定欄位內含控件項的動作一定要在 RowCreated 事件中處理;不能在 RowDataBound 事件中處理,因為
RowDataBound 事件只有在 GridView 執行 DataBind 的動作時才會觸發,而 RowCreated 事件是每次頁面
PostBack 時重新產生 GridView 時都會觸發。

抱歉!评论已关闭.