GridView.AutoGenerateSelectButton GridView.AutoGenerateSelectButton GridView.AutoGenerateSelectButton GridView.AutoGenerateSelectButton Property

Definición

Obtiene o establece un valor que indica si una columna de campo CommandField con un botón Seleccionar para cada fila de datos se agrega automáticamente a un control GridView.Gets or sets a value indicating whether a CommandField field column with a Select button for each data row is automatically added to a GridView control.

public:
 virtual property bool AutoGenerateSelectButton { bool get(); void set(bool value); };
public virtual bool AutoGenerateSelectButton { get; set; }
member this.AutoGenerateSelectButton : bool with get, set
Public Overridable Property AutoGenerateSelectButton As Boolean

Valor de propiedad

Es true para agregar automáticamente una columna de campo CommandField con un botón Seleccionar para cada fila de datos; de lo contrario, es false.true to automatically add a CommandField field column with a Select button for each data row; otherwise, false. De manera predeterminada, es false.The default is false.

Ejemplos

En el ejemplo siguiente se muestra cómo utilizar AutoGenerateSelectButton la propiedad para habilitar la característica GridView de selección automática del control.The following example demonstrates how to use the AutoGenerateSelectButton property to enable the automatic selection feature of the GridView control.


<%@ 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 CustomersGridView_SelectedIndexChanged(Object sender, EventArgs e)
  {
    // Get the currently selected row using the SelectedRow property.
    GridViewRow row = CustomersGridView.SelectedRow;
        
    // Display the first name from the selected row.
    // In this example, the third column (index 2) contains
    // the first name.
    MessageLabel.Text = "You selected " + row.Cells[2].Text + ".";
  }

  void CustomersGridView_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
  {
    // Get the currently selected row. Because the SelectedIndexChanging event
    // occurs before the select operation in the GridView control, the
    // SelectedRow property cannot be used. Instead, use the Rows collection
    // and the NewSelectedIndex property of the e argument passed to this 
    // event handler.
    GridViewRow row = CustomersGridView.Rows[e.NewSelectedIndex];

    // You can cancel the select operation by using the Cancel
    // property. For this example, if the user selects a customer with 
    // the ID "ANATR", the select operation is canceled and an error message
    // is displayed.
    if (row.Cells[1].Text == "ANATR")
    {
      e.Cancel = true;
      MessageLabel.Text = "You cannot select " + row.Cells[2].Text + "."; 
    }
  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>GridView Select Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
     <h3>GridView Select Example</h3>

     <asp:gridview id="CustomersGridView" 
       datasourceid="CustomersSource" 
       autogeneratecolumns="False"
       autogenerateselectbutton="True"
       selectedindex="1"
       onselectedindexchanged="CustomersGridView_SelectedIndexChanged"
       onselectedindexchanging="CustomersGridView_SelectedIndexChanging"   
       runat="server" DataKeyNames="CustomerID">
                
         <Columns>
             <asp:BoundField DataField="CustomerID" 
                 HeaderText="CustomerID" 
                 InsertVisible="False" ReadOnly="True" 
                 SortExpression="CustomerID" />
             <asp:BoundField DataField="FirstName" 
                 HeaderText="FirstName" 
                 SortExpression="FirstName" />
             <asp:BoundField DataField="MiddleName" 
                 HeaderText="MiddleName" 
                 SortExpression="MiddleName" />
             <asp:BoundField DataField="LastName" 
                 HeaderText="LastName" 
                 SortExpression="LastName" />
             <asp:BoundField DataField="Phone" 
                 HeaderText="Phone" 
                 SortExpression="Phone" />
         </Columns>
                
       <selectedrowstyle backcolor="LightCyan"
         forecolor="DarkBlue"
         font-bold="true"/>  
                
     </asp:gridview>
            
      <br/>
            
      <asp:label id="MessageLabel"
        forecolor="Red"
        runat="server"/>
            
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="CustomersSource"
        selectcommand="SELECT CustomerID, FirstName, MiddleName, LastName, Phone FROM SalesLT.Customer"
        connectionstring="<%$ ConnectionStrings:AdventureWorksLTConnectionString %>" 
        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 CustomersGridView_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        
    ' Get the currently selected row using the SelectedRow property.
    Dim row As GridViewRow = CustomersGridView.SelectedRow
        
    ' Display the first name from the selected row.
    ' In this example, the third column (index 2) contains
    ' the first name.
    MessageLabel.Text = "You selected " & row.Cells(2).Text & "."
  End Sub

  Sub CustomersGridView_SelectedIndexChanging(ByVal sender As Object, ByVal e As GridViewSelectEventArgs)
        
    ' Get the currently selected row. Because the SelectedIndexChanging event
    ' occurs before the select operation in the GridView control, the
    ' SelectedRow property cannot be used. Instead, use the Rows collection
    ' and the NewSelectedIndex property of the e argument passed to this 
    ' event handler.
    Dim row As GridViewRow = CustomersGridView.Rows(e.NewSelectedIndex)

    ' You can cancel the select operation by using the Cancel
    ' property. For this example, if the user selects a customer with 
    ' the ID "ANATR", the select operation is canceled and an error message
    ' is displayed.
    If row.Cells(1).Text = "ANATR" Then
        e.Cancel = True
        MessageLabel.Text = "You cannot select " + row.Cells(2).Text & "."
    End If
    
  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>GridView Select Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
     <h3>GridView Select Example</h3>

     <asp:gridview id="CustomersGridView" 
       datasourceid="CustomersSource" 
       autogeneratecolumns="False"
       autogenerateselectbutton="True"
       selectedindex="1"
       onselectedindexchanged="CustomersGridView_SelectedIndexChanged"
       onselectedindexchanging="CustomersGridView_SelectedIndexChanging"   
       runat="server" DataKeyNames="CustomerID">
                
         <Columns>
             <asp:BoundField DataField="CustomerID" 
                 HeaderText="CustomerID" 
                 InsertVisible="False" ReadOnly="True" 
                 SortExpression="CustomerID" />
             <asp:BoundField DataField="FirstName" 
                 HeaderText="FirstName" 
                 SortExpression="FirstName" />
             <asp:BoundField DataField="MiddleName" 
                 HeaderText="MiddleName" 
                 SortExpression="MiddleName" />
             <asp:BoundField DataField="LastName" 
                 HeaderText="LastName" 
                 SortExpression="LastName" />
             <asp:BoundField DataField="Phone" 
                 HeaderText="Phone" 
                 SortExpression="Phone" />
         </Columns>
                
       <selectedrowstyle backcolor="LightCyan"
         forecolor="DarkBlue"
         font-bold="true"/>  
                
     </asp:gridview>
            
      <br/>
            
      <asp:label id="MessageLabel"
        forecolor="Red"
        runat="server"/>
            
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="CustomersSource"
        selectcommand="SELECT CustomerID, FirstName, MiddleName, LastName, Phone FROM SalesLT.Customer"
        connectionstring="<%$ ConnectionStrings:AdventureWorksLTConnectionString %>" 
        runat="server"/>
            
    </form>

  </body>
</html>

Comentarios

Cuando la AutoGenerateSelectButton propiedad está establecida en true, se agrega automáticamente al GridView control una CommandField columna (representada por un objeto) con un botón Seleccionar para cada fila de datos.When the AutoGenerateSelectButton property is set to true, a column (represented by a CommandField object) with a Select button for each data row is automatically added to the GridView control. Al hacer clic en el botón seleccionar de una fila, se selecciona esa fila en el SelectedIndex control, que establece la propiedad en el índice de la fila.Clicking the Select button for a row selects that row in the control, which sets the SelectedIndex property to the index of the row. Para recuperar el GridViewRow objeto que representa la fila seleccionada, use la SelectedRow propiedad.To retrieve the GridViewRow object that represents the selected row, use the SelectedRow property. También puede obtener el valor de la clave principal para el registro seleccionado mediante la SelectedValue propiedad.You can also get the primary key value for the selected record by using the SelectedValue property. La SelectedValue propiedad contiene los valores de los campos de clave especificados DataKeyNames en la propiedad.The SelectedValue property contains the values of the key fields specified in the DataKeyNames property.

Nota

Puede seleccionar una fila mediante programación estableciendo la SelectedIndex propiedad.You can programmatically select a row by setting the SelectedIndex property. Para cancelar la selección de una fila, establezca la SelectedIndex propiedad en-1.To cancel the selection of a row, set the SelectedIndex property to -1.

Puede controlar la apariencia de la fila seleccionada mediante la SelectedRowStyle propiedad.You can control the appearance of the selected row by using the SelectedRowStyle property. La configuración común suele incluir un color de fondo personalizado, un color de primer plano y propiedades de fuente.Common settings usually include a custom background color, foreground color, and font properties.

El GridView control proporciona varios eventos que se pueden usar para realizar una acción personalizada cuando se selecciona una fila.The GridView control provides several events that you can use to perform a custom action when a row is selected. En la tabla siguiente se enumeran los eventos disponibles.The following table lists the available events.

eventoEvent DescripciónDescription
SelectedIndexChanged Se produce cuando se hace clic en el botón Seleccionar de una fila, pero después de que el control GridView se ocupe de la operación de selección.Occurs when a row's Select button is clicked, but after the GridView control handles the select operation. Este evento suele usarse para realizar una tarea después de seleccionar una fila en el control.This event is often used to perform a task after a row is selected in the control.
SelectedIndexChanging Se produce cuando se hace clic en el botón Seleccionar de una fila, pero antes de que el control GridView se ocupe de la operación de selección.Occurs when a row's Select button is clicked, but before the GridView control handles the select operation. Este evento suele usarse para cancelar la operación de selección.This event is often used to cancel the selecting operation.

Se aplica a

Consulte también: