在ASP.NET中, GridView用來顯示數據,datasource用來獲取,刪除,插入數據。不過,有時我們不需要datasource來處理刪除或插入等操作。比如我們需要對被刪除的數據進行判斷。
row command是負責處理數據編輯,插入,刪除的。
我們可以在protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)事件中得到當前的Command Name和Command Paramter。
Command Name命令指示要執行的操作,如刪除,Command Paramter指示操作的參數,如當前記錄的ID號。
CommandName value |
Description |
---|---|
"Cancel" |
Cancels an edit operation and returns the GridView control to read-only mode. Raises the RowCancelingEdit event. |
"Delete" |
Deletes the current record. Raises the RowDeleting and RowDeleted events. |
"Edit" |
Puts the current record in edit mode. Raises the RowEditing event. |
"Page" |
Performs a paging operation. Sets the CommandArgument property of the button to "First", "Last", "Next", "Prev", or a page number to specify the type of paging operation to perform. Raises the PageIndexChanging and PageIndexChanged events. |
"Select" |
Selects the current record. Raises the SelectedIndexChanging and SelectedIndexChanged events. |
"Sort" |
Sorts the GridView control. Raises the Sorting and Sorted events. |
"Update" |
Updates the current record in the data source. Raises the RowUpdating and RowUpdated events. |
默認情況,在Gridview模板自動生成的刪除按鈕,會將CommandName=“Delete”。
我們要作的就是爲刪除按鈕指定一個不同的CommandName,然後在protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)事件中自己處理這個自定義的Command Name。
ASPX頁面如下
<
asp:TemplateField HeaderText="Delete"><ItemTemplate>
<asp:Button ID="ButtonDelete" runat="server" Text="Delete" CommandName="DeleteUser" CommandArgument='<%# Bind("UserName") %>' OnClientClick="return confirm('Are you sure to delete this user?')" />
</ItemTemplate>
CODE代碼如下
protected
{
void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)//delete a user
{
SESG.Security.
GridView1.DataBind();
GridView1.SelectedIndex = -1;
}
}
if ("DeleteUser" == e.CommandName)string alias = e.CommandArgument.ToString();SESGMemberShip.DeleteUser(alias);</asp:TemplateField>