GridView.RowCommand 事件

定义

当单击 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” 删除当前记录。 引发 RowDeletingRowDeleted 事件。
“编辑” 将当前记录置于编辑模式。 引发 RowEditing 事件。
“Page” 执行分页操作。 将 CommandArgument 按钮的 属性设置为“First”、“Last”、“Next”、“Prev”或页码,以指定要执行的分页操作的类型。 引发 PageIndexChangingPageIndexChanged 事件。
“选择” 选择当前记录。 引发 SelectedIndexChangingSelectedIndexChanged 事件。
“Sort” GridView 控件进行排序。 引发 SortingSorted 事件。
“更新” 更新数据源中的当前记录。 引发 RowUpdatingRowUpdated 事件。

RowCommand虽然单击上表中列出的按钮时会引发事件,但建议使用表中列出的事件执行操作。

对象 GridViewCommandEventArgs 将传递给事件处理方法,这使你可以确定所单击按钮的命令名称和命令参数。

备注

若要确定引发事件的行的索引,请使用 CommandArgument 传递给事件的事件参数的 属性。 类 ButtonField 会自动使用适当的索引值填充 CommandArgument 属性。 对于其他命令按钮,必须手动设置 CommandArgument 命令按钮的 属性。 例如,当控件未启用分页时GridView,可以将 设置为 。CommandArgument<%# Container.DataItemIndex %>

有关如何处理事件的详细信息,请参阅 处理和引发事件

适用于

另请参阅