GridView.AutoGenerateSelectButton Proprietà

Definizione

Ottiene o imposta un valore che indica se a un controllo CommandField viene aggiunta automaticamente una colonna associata a campo GridView con un pulsante Seleziona per ciascuna riga di dati.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

Valore della proprietà

Boolean

true per aggiungere automaticamente una colonna associata a campo CommandField con un pulsante Seleziona per ciascuna riga di dati, altrimenti false.true to automatically add a CommandField field column with a Select button for each data row; otherwise, false. Il valore predefinito è false.The default is false.

Esempio

Nell'esempio seguente viene illustrato come utilizzare la AutoGenerateSelectButton proprietà per abilitare la funzionalità di selezione automatica del GridView controllo.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>

Commenti

Quando la AutoGenerateSelectButton proprietà è impostata su true , al controllo viene aggiunta automaticamente una colonna, rappresentata da un CommandField oggetto, con un pulsante di selezione per ogni riga di dati GridView .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. Facendo clic sul pulsante Seleziona per una riga, viene selezionata la riga nel controllo, che imposta la SelectedIndex proprietà sull'indice della riga.Clicking the Select button for a row selects that row in the control, which sets the SelectedIndex property to the index of the row. Per recuperare l' GridViewRow oggetto che rappresenta la riga selezionata, utilizzare la SelectedRow Proprietà.To retrieve the GridViewRow object that represents the selected row, use the SelectedRow property. È anche possibile ottenere il valore della chiave primaria per il record selezionato usando la SelectedValue Proprietà.You can also get the primary key value for the selected record by using the SelectedValue property. La SelectedValue proprietà contiene i valori dei campi chiave specificati nella DataKeyNames Proprietà.The SelectedValue property contains the values of the key fields specified in the DataKeyNames property.

Nota

È possibile selezionare una riga a livello di codice impostando la SelectedIndex Proprietà.You can programmatically select a row by setting the SelectedIndex property. Per annullare la selezione di una riga, impostare la SelectedIndex proprietà su-1.To cancel the selection of a row, set the SelectedIndex property to -1.

È possibile controllare l'aspetto della riga selezionata utilizzando la SelectedRowStyle Proprietà.You can control the appearance of the selected row by using the SelectedRowStyle property. Le impostazioni comuni includono generalmente un colore di sfondo personalizzato, un colore di primo piano e le proprietà del tipo di carattere.Common settings usually include a custom background color, foreground color, and font properties.

Il GridView controllo fornisce diversi eventi che è possibile usare per eseguire un'azione personalizzata quando viene selezionata una riga.The GridView control provides several events that you can use to perform a custom action when a row is selected. Nella tabella seguente sono elencati gli eventi disponibili.The following table lists the available events.

EventEvent DescrizioneDescription
SelectedIndexChanged Si verifica quando viene fatto clic sul pulsante Seleziona di una riga, ma dopo che il controllo GridView ha gestito l'operazione di selezione.Occurs when a row's Select button is clicked, but after the GridView control handles the select operation. Questo evento viene spesso utilizzato per eseguire un'attività dopo che è stata selezionata una riga nel controllo.This event is often used to perform a task after a row is selected in the control.
SelectedIndexChanging Si verifica quando viene fatto clic sul pulsante Seleziona di una riga, ma prima che il controllo GridView gestisca l'operazione di selezione.Occurs when a row's Select button is clicked, but before the GridView control handles the select operation. Questo evento viene spesso usato per annullare l'operazione di selezione.This event is often used to cancel the selecting operation.

Si applica a

Vedi anche