GridView.RowCommand 事件
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
按一下 GridView 控制項中的按鈕時發生。
public:
event System::Web::UI::WebControls::GridViewCommandEventHandler ^ RowCommand;
public event System.Web.UI.WebControls.GridViewCommandEventHandler RowCommand;
member this.RowCommand : System.Web.UI.WebControls.GridViewCommandEventHandler
Public Custom Event RowCommand As GridViewCommandEventHandler
事件類型
範例
具有原始程式碼的 Visual Studio 網站專案隨附于本主題: 下載。
下列範例示範如何使用 RowCommand 事件,在按一下資料列的 [新增] 按鈕時,將 GridView 控制項中的客戶名稱新增至 ListBox 控制項。
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Add")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = ContactsGridView.Rows[index];
// Create a new ListItem object for the contact in the row.
ListItem item = new ListItem();
item.Text = Server.HtmlDecode(row.Cells[2].Text) + " " +
Server.HtmlDecode(row.Cells[3].Text);
// If the contact is not already in the ListBox, add the ListItem
// object to the Items collection of the ListBox control.
if (!ContactsListBox.Items.Contains(item))
{
ContactsListBox.Items.Add(item);
}
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView RowCommand Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridView RowCommand Example</h3>
<table width="100%">
<tr>
<td style="width:50%">
<asp:gridview id="ContactsGridView"
datasourceid="ContactsSource"
allowpaging="true"
autogeneratecolumns="false"
onrowcommand="ContactsGridView_RowCommand"
runat="server">
<columns>
<asp:buttonfield buttontype="Link"
commandname="Add"
text="Add"/>
<asp:boundfield datafield="ContactID"
headertext="Contact ID"/>
<asp:boundfield datafield="FirstName"
headertext="First Name"/>
<asp:boundfield datafield="LastName"
headertext="Last Name"/>
</columns>
</asp:gridview>
</td>
<td style="vertical-align:top; width:50%">
Contacts: <br/>
<asp:listbox id="ContactsListBox"
runat="server" Height="200px" Width="200px"/>
</td>
</tr>
</table>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="ContactsSource"
selectcommand="Select [ContactID], [FirstName], [LastName] From Person.Contact"
connectionstring="<%$ ConnectionStrings:AdventureWorks_DataConnectionString%>"
runat="server"/>
</form>
</body>
</html>
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub ContactsGridView_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
' If multiple buttons are used in a GridView control, use the
' CommandName property to determine which button was clicked.
If e.CommandName = "Add" Then
' Convert the row index stored in the CommandArgument
' property to an Integer.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button clicked
' by the user from the Rows collection.
Dim row As GridViewRow = ContactsGridView.Rows(index)
' Create a new ListItem object for the contact in the row.
Dim item As New ListItem()
item.Text = Server.HtmlDecode(row.Cells(2).Text) & " " & _
Server.HtmlDecode(row.Cells(3).Text)
' If the contact is not already in the ListBox, add the ListItem
' object to the Items collection of the ListBox control.
If Not ContactsListBox.Items.Contains(item) Then
ContactsListBox.Items.Add(item)
End If
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>GridView RowCommand Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridView RowCommand Example</h3>
<table width="100%">
<tr>
<td style="width:50%">
<asp:gridview id="ContactsGridView"
datasourceid="ContactsSource"
allowpaging="true"
autogeneratecolumns="false"
onrowcommand="ContactsGridView_RowCommand"
runat="server">
<columns>
<asp:buttonfield buttontype="Link"
commandname="Add"
text="Add"/>
<asp:boundfield datafield="ContactID"
headertext="Contact ID"/>
<asp:boundfield datafield="FirstName"
headertext="First Name"/>
<asp:boundfield datafield="LastName"
headertext="Last Name"/>
</columns>
</asp:gridview>
</td>
<td style="vertical-align:top; width:50%">
Contacts: <br/>
<asp:listbox id="ContactsListBox"
runat="server" Height="200px" Width="200px"/>
</td>
</tr>
</table>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="ContactsSource"
selectcommand="Select [ContactID], [FirstName], [LastName] From Person.Contact"
connectionstring="<%$ ConnectionStrings:AdventureWorks_DataConnectionString%>"
runat="server"/>
</form>
</body>
</html>
下列範例示範如何在按下資料列的按鈕時,使用 RowCommand 事件來更新產品的價格。 此範例已啟用 GridView 控制項的分頁功能,並將 控制項的 Button 屬性設定 CommandArgument 為適當的資料列索引。
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void ProductsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Increase")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = ProductsGridView.Rows[index];
// Calculate the new price.
Label listPriceTextBox = (Label)row.FindControl("PriceLabel");
listPriceTextBox.Text = (Convert.ToDouble(listPriceTextBox.Text) * 1.05).ToString();
// Update the row.
ProductsGridView.UpdateRow(index, false);
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView RowCommand Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridView RowCommand Example</h3>
<asp:GridView id="ProductsGridView"
DataSourceID="ProductsDataSource"
DataKeyNames="ProductID"
AllowPaging="True"
OnRowCommand="ProductsGridView_RowCommand"
AutoGenerateColumns="False"
runat="server">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Product Name" />
<asp:BoundField DataField="ProductNumber" HeaderText="Product Number" />
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="PriceLabel" runat="server"
Text='<%# Bind("ListPrice") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="IncreaseButton"
Text="Increase Price 5%"
CommandName="Increase"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:SqlDataSource id="ProductsDataSource"
SelectCommand="SELECT [ProductID], [Name], [ProductNumber], [ListPrice]
FROM Production.Product
WHERE ListPrice <> 0"
UpdateCommand="UPDATE Production.Product SET [ListPrice] = @ListPrice
WHERE [ProductID] = @ProductID"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
runat="server" />
</form>
</body>
</html>
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub ProductsGridView_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
' If multiple buttons are used in a GridView control, use the
' CommandName property to determine which button was clicked.
If e.CommandName = "Increase" Then
' Convert the row index stored in the CommandArgument
' property to an Integer.
Dim index = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button clicked
' by the user from the Rows collection.
Dim row = ProductsGridView.Rows(index)
' Calculate the new price.
Dim listPriceTextBox = CType(row.FindControl("PriceLabel"), Label)
listPriceTextBox.Text = (Convert.ToDouble(listPriceTextBox.Text) * 1.05).ToString()
' Update the row.
ProductsGridView.UpdateRow(index, False)
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView RowCommand Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridView RowCommand Example</h3>
<asp:GridView id="ProductsGridView"
DataSourceID="ProductsDataSource"
DataKeyNames="ProductID"
AllowPaging="True"
OnRowCommand="ProductsGridView_RowCommand"
AutoGenerateColumns="False"
runat="server">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Product Name" />
<asp:BoundField DataField="ProductNumber" HeaderText="Product Number" />
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="PriceLabel" runat="server"
Text='<%# Bind("ListPrice") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="IncreaseButton"
Text="Increase Price 5%"
CommandName="Increase"
CommandArgument="<%# CType(Container, GridViewRow).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:SqlDataSource id="ProductsDataSource"
SelectCommand="SELECT [ProductID], [Name], [ProductNumber], [ListPrice]
FROM Production.Product
WHERE ListPrice <> 0"
UpdateCommand="UPDATE Production.Product SET [ListPrice] = @ListPrice
WHERE [ProductID] = @ProductID"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
runat="server" />
</form>
</body>
</html>
備註
RowCommand按一下 控制項中的 GridView 按鈕時,就會引發 事件。 這可讓您提供事件處理方法,每當發生此事件時,都會執行自訂常式。
控制項內的 GridView 按鈕也可以叫用控制項的一些內建功能。 若要執行其中一項作業,請將 CommandName
按鈕的 屬性設定為下表中的其中一個值。
CommandName 值 |
描述 |
---|---|
「取消」 | 取消編輯作業,並將控制項傳回 GridView 唯讀模式。 引發 RowCancelingEdit 事件。 |
"Delete" | 刪除目前記錄。 RowDeleting引發 和 RowDeleted 事件。 |
「編輯」 | 將目前記錄置於編輯模式中。 引發 RowEditing 事件。 |
「Page」 | 執行分頁作業。 將 CommandArgument 按鈕的 屬性設定為 「First」、「Last」、「Next」、「Prev」 或頁碼,以指定要執行的分頁作業類型。
PageIndexChanging引發 和 PageIndexChanged 事件。 |
"Select" | 選取目前記錄。 SelectedIndexChanging引發 和 SelectedIndexChanged 事件。 |
「Sort」 | 排序 GridView 控制項。 Sorting引發 和 Sorted 事件。 |
「Update」 | 更新資料來源中目前的資料錄。 RowUpdating引發 和 RowUpdated 事件。 |
RowCommand雖然按一下上表所列的按鈕時會引發事件,但建議您使用資料表中所列的事件來進行作業。
GridViewCommandEventArgs物件會傳遞至事件處理方法,可讓您判斷按下按鈕的命令名稱和命令引數。
注意
若要判斷引發事件之資料列的索引,請使用 CommandArgument 傳遞至事件之事件引數的 屬性。 類別 ButtonField 會自動將適當的索引值填入 CommandArgument 屬性。 對於其他命令按鈕,您必須手動設定 CommandArgument 命令按鈕的 屬性。 例如,當控制項未啟用分頁時 GridView ,您可以將 設定 CommandArgument 為 <%# Container.DataItemIndex %>
。
如需如何處理事件的詳細資訊,請參閱 處理和引發事件。