在gridview中,我們都希望能在刪除記錄時,能彈出提示框予以提示,在asp.net 1.1中,都可以很容易實現(xiàn),那么在asp.net 2.0中要如何實現(xiàn)呢?下面舉例子說明,首先在HTML頁面中設計好如下代碼:
<asp:GridView DataKeyNames="CategoryID" ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" OnRowDeleted="GridView1_RowDeleted" OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" CommandArgument=‘<%# Eval("CategoryID") %>‘ CommandName="Delete" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
在上面的代碼中,我們設置了一個鏈接linkbutton,其中指定了commandname為"Delete",commandargument為要刪除的記錄的ID編號,注意一旦commandname設置為delete這個名稱后,gridview中的GridView_RowCommand 和 GridView_Row_Deleting 事件都會被激發(fā)接者,我們處理其rowdatabound事件中:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
l.Attributes.Add(‘onclick", "javascript:return " + "confirm("是否要刪除該記錄? " +
DataBinder.Eval(e.Row.DataItem, "id") + "‘)");
}
}
在這段代碼中,首先檢查是否是datarow,是的話則得到每個linkbutton,再為其添加客戶端代碼,基本和asp.net 1.1的做法差不多。
之后,當用戶選擇了確認刪除后,我們有兩種方法對其進行繼續(xù)的后續(xù)刪除處理,因為我們將刪除按鈕設置為Delete,方法一是在row_command事件中寫入如下代碼:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int id = Convert.ToInt32(e.CommandArgument);
// 刪除記錄的專門過程
DeleteRecordByID(id);
}
}
另外一種方法是使用gridview的row_deletting事件,先在頁面HTML代碼中,添加<asp:GridView DataKeyNames="CategoryID" ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" onRowDeleting="GridView1_RowDeleting">
然后添加row_deleting事件:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int categoryID = (int) GridView1.DataKeys[e.RowIndex].Value;
DeleteRecordByID(categoryID);
}
要注意的是,這個必須將datakeynames設置為要刪除記錄的編號,這里是categoryid.