ASP.NET中GridView控件ButtonField的使用
在ASP.NET的GridView控件中使用ButtonField列,通過當前行數據綁定按鈕的顯示文字,即按鈕的text屬性,以及對應的后台單擊事件。
1.前台頁面部分代碼
1 <asp:GridView runat="server" ID="GridViewBooks" AutoGenerateColumns="false" CellPadding="4" 2 OnRowCommand="GridView_OnRowCommand" 3 AllowSorting="true" > 4 <Columns > 5 <asp:BoundField DataField ="ID" HeaderText="ID" ReadOnly = "true" /> 6 <asp:BoundField DataField="name" HeaderText="書名" ReadOnly ="true" /> 7 <asp:BoundField DataField="count" HeaderText="數量" ReadOnly ="true" /> 8 <asp:BoundField DataField="status" HeaderText="狀態" ReadOnly ="true" /> 9 <asp:ButtonField ButtonType="Button" Text="借" HeaderText="操作" CommandName="Btn_Operation" /> 10 </Columns> 11 <%--... --%> 12 </asp:GridView>
在GridView控件中添加ButtonField列,並設置按鈕類型、(為Button(普通按鈕))、顯示文本(可以不用設置)、列名、以及傳遞的參數(這里設置的是CommandName,用來唯一標識列),在GridView屬性中添加OnRowCommand事件。
2.后台實現
1 protected void GridView_OnRowCommand(object sender, GridViewCommandEventArgs e) 2 { 3 if (e.CommandName == "Btn_Operation") 4 { 5 int index = Convert.ToInt32(e.CommandArgument); 6 //... 7 8 } 9 }
這里ButtonField 類自動以適當的索引值填充 CommandArgument 屬性,即e.CommandArgument值為GirdView當前的行號(從0開始);e.Command為列的CommandName屬性。
2015年12月28日11:27:01