GridView.RowCommand Evento

Definición

Se produce cuando se hace clic en un botón de un control 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 

Tipo de evento

Ejemplos

Hay disponible un proyecto de sitio web de Visual Studio con código fuente para acompañar este tema: Descargar.

En el ejemplo siguiente se muestra cómo usar el RowCommand evento para agregar el nombre de un cliente de un GridView control a un control cuando se hace clic en el botón Agregar de una ListBox fila.


<%@ 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>

En el ejemplo siguiente se muestra cómo usar el RowCommand evento para actualizar el precio de un producto cuando se hace clic en el botón de una fila. En este ejemplo se habilita la funcionalidad de paginación para el GridView control y se establece la CommandArgument propiedad del control en el índice de Button fila adecuado.


<%@ 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>

Comentarios

El RowCommand evento se genera cuando se hace clic en un botón en el GridView control . Esto le permite proporcionar un método de control de eventos que realiza una rutina personalizada cada vez que se produce este evento.

Los botones de un GridView control también pueden invocar algunas de las funciones integradas del control. Para realizar una de estas operaciones, establezca la CommandName propiedad de un botón en uno de los valores de la tabla siguiente.

Valor de CommandName Descripción
"Cancelar" Cancela una operación de edición y devuelve el GridView control al modo de solo lectura. Genera el evento RowCancelingEdit.
“Eliminar” Elimina el registro actual. Genera los RowDeleting eventos y RowDeleted .
"Editar" Coloca el registro actual en modo de edición. Genera el evento RowEditing.
"Página" Realiza una operación de paginación. Establece la CommandArgument propiedad del botón en "First", "Last", "Next", "Prev" o un número de página para especificar el tipo de operación de paginación que se va a realizar. Genera los PageIndexChanging eventos y PageIndexChanged .
"Seleccionar" Selecciona el registro actual. Genera los SelectedIndexChanging eventos y SelectedIndexChanged .
"Ordenar" Ordena el GridView control . Genera los Sorting eventos y Sorted .
"Actualizar" Actualiza el registro actual en el origen de datos. Genera los RowUpdating eventos y RowUpdated .

Aunque se genera el RowCommand evento cuando se hace clic en un botón que aparece en la tabla anterior, se recomienda usar los eventos enumerados en la tabla para la operación.

Un GridViewCommandEventArgs objeto se pasa al método de control de eventos, lo que le permite determinar el nombre del comando y el argumento de comando del botón en el que se hace clic.

Nota:

Para determinar el índice de la fila que generó el evento, use la CommandArgument propiedad del argumento de evento que se pasa al evento. La ButtonField clase rellena automáticamente la CommandArgument propiedad con el valor de índice adecuado. Para otros botones de comando, debe establecer manualmente la CommandArgument propiedad del botón de comando. Por ejemplo, puede establecer en CommandArgument<%# Container.DataItemIndex %> cuando el GridView control no tenga habilitada la paginación.

Para obtener más información acerca de cómo controlar eventos, vea controlar y provocar eventos.

Se aplica a

Consulte también