ListView.ItemCommand Evento

Definizione

Si verifica quando viene fatto clic su un pulsante in un controllo ListView.Occurs when a button in a ListView control is clicked.

public:
 event EventHandler<System::Web::UI::WebControls::ListViewCommandEventArgs ^> ^ ItemCommand;
public event EventHandler<System.Web.UI.WebControls.ListViewCommandEventArgs> ItemCommand;
member this.ItemCommand : EventHandler<System.Web.UI.WebControls.ListViewCommandEventArgs> 
Public Custom Event ItemCommand As EventHandler(Of ListViewCommandEventArgs) 

Esempi

Nell'esempio seguente viene illustrato come creare un ItemCommand gestore eventi.The following example shows how to create an ItemCommand event handler.

<%@ 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">
  protected void EmployeesListView_OnItemCommand(object sender, ListViewCommandEventArgs e)
  {
    if (String.Equals(e.CommandName, "AddToList"))
    {
      // Verify that the employee ID is not already in the list. If not, add the
      // employee to the list.
      ListViewDataItem dataItem = (ListViewDataItem)e.Item;
      string employeeID = 
        EmployeesListView.DataKeys[dataItem.DisplayIndex].Value.ToString();
      
      if (SelectedEmployeesListBox.Items.FindByValue(employeeID) == null)
      {
        ListItem item = new ListItem(e.CommandArgument.ToString(), employeeID);
        SelectedEmployeesListBox.Items.Add(item);
      }
    }
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Employee List</title>
  </head>
  <body>
    <form id="form1" runat="server">
      <asp:ListView runat="server" 
        ID="EmployeesListView"
        OnItemCommand="EmployeesListView_OnItemCommand"
        DataSourceID="EmployeesDataSource" 
        DataKeyNames="EmployeeID">
        <LayoutTemplate>
          <table runat="server" id="tblEmployees" 
                 cellspacing="0" cellpadding="1" width="440px" border="1">
            <tr id="itemPlaceholder" runat="server"></tr>
          </table>
          <asp:DataPager ID="EmployeesDataPager" runat="server" PageSize="10">
            <Fields>
              <asp:NumericPagerField />
            </Fields>
          </asp:DataPager>
        </LayoutTemplate>
        <ItemTemplate>
          <tr runat="server">
            <td>
              <asp:Label runat="server" ID="NameLabel" 
                Text='<%#Eval("LastName") + ", " + Eval("FirstName") %>' />
            </td>
            <td style="width:80px">
              <asp:LinkButton runat="server" 
                ID="SelectEmployeeButton" 
                Text="Add To List" 
                CommandName="AddToList" 
                CommandArgument='<%#Eval("LastName") + ", " + Eval("FirstName") %>' />
            </td>
          </tr>
        </ItemTemplate>
      </asp:ListView>
      
      <br /><br />
      <b>Selected Employees:</b><br />
      <asp:ListBox runat="server" ID="SelectedEmployeesListBox" Rows="10" Width="300px" />
       
      <!-- 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="EmployeesDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
        SelectCommand="SELECT [EmployeeID], [FirstName], [LastName]
                       FROM HumanResources.vEmployee
                       ORDER BY [LastName], [FirstName], [EmployeeID]">
      </asp:SqlDataSource>
    </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">
  Protected Sub EmployeesListView_OnItemCommand(ByVal sender As Object, _
  ByVal e As ListViewCommandEventArgs)
    
    If String.Equals(e.CommandName, "AddToList") Then
      
      ' Verify that the employee ID is not already in the list. If not, add the
      ' employee to the list.
      Dim dataItem As ListViewDataItem = CType(e.Item, ListViewDataItem)
      Dim employeeID As String = _
        EmployeesListView.DataKeys(dataItem.DisplayIndex).Value.ToString()
      
      If SelectedEmployeesListBox.Items.FindByValue(employeeID) Is Nothing Then
        Dim item As ListItem = _
          New ListItem(e.CommandArgument.ToString(), employeeID)
        SelectedEmployeesListBox.Items.Add(item)
      End If
      
    End If
    
  End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head2" runat="server">
    <title>Employee List</title>
  </head>
  <body>
    <form id="form1" runat="server">
      <asp:ListView runat="server" 
        ID="EmployeesListView"
        OnItemCommand="EmployeesListView_OnItemCommand"
        DataSourceID="EmployeesDataSource" 
        DataKeyNames="EmployeeID">
        <LayoutTemplate>
          <table runat="server" id="tblEmployees" 
                 cellspacing="0" cellpadding="1" width="440px" border="1">
            <tr id="itemPlaceholder" runat="server"></tr>
          </table>
          <asp:DataPager ID="EmployeesDataPager" runat="server" PageSize="10">
            <Fields>
              <asp:NumericPagerField />
            </Fields>
          </asp:DataPager>
        </LayoutTemplate>
        <ItemTemplate>
          <tr runat="server">
            <td>
              <asp:Label runat="server" ID="NameLabel" 
                Text='<%#Eval("LastName") & ", " & Eval("FirstName") %>' />
            </td>
            <td style="width:80px">
              <asp:LinkButton runat="server" 
                ID="SelectEmployeeButton" 
                Text="Add To List" 
                CommandName="AddToList" 
                CommandArgument='<%#Eval("LastName") & ", " & Eval("FirstName") %>' />
            </td>
          </tr>
        </ItemTemplate>
      </asp:ListView>
      
      <br /><br />
      <b>Selected Employees:</b><br />
      <asp:ListBox runat="server" ID="SelectedEmployeesListBox" Rows="10" Width="300px" />
       
      <!-- 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="EmployeesDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
        SelectCommand="SELECT [EmployeeID], [FirstName], [LastName]
                       FROM HumanResources.vEmployee
                       ORDER BY [LastName], [FirstName], [EmployeeID]">
      </asp:SqlDataSource>
    </form>
  </body>
</html>

Commenti

L' ItemCommand evento viene generato quando si fa clic su ListView un pulsante nel controllo.The ItemCommand event is raised when a button in the ListView control is clicked. In questo modo è possibile eseguire una routine personalizzata ogni volta che si verifica questo evento.This enables you to perform a custom routine whenever this event occurs.

I pulsanti in ListView un controllo possono anche richiamare la funzionalità incorporata del controllo.Buttons in a ListView control can also invoke built-in functionality of the control. Nella tabella seguente sono elencati i valori che è possibile utilizzare CommandName con la proprietà di un pulsante per richiamare la funzionalità incorporata.The following table lists values that you can use with the CommandName property of a button in order to invoke built-in functionality.

Valore CommandNameCommandName value DescriptionDescription
Annullare"Cancel" Annulla un'operazione di modifica o inserimento.Cancels an edit or insert operation. Genera l'evento ItemCanceling.Raises the ItemCanceling event.
"Delete""Delete" Elimina il record corrente dall'origine dati.Deletes the current record from the data source. Genera gli ItemDeleted eventi ItemDeleting e.Raises the ItemDeleted and ItemDeleting events.
Selezionare"Select" Imposta la SelectedIndex proprietà DisplayIndex sul valore della proprietà per l'elemento.Sets the SelectedIndex property to the DisplayIndex property value for the item. Esegue il rendering SelectedItemTemplate del modello per l'elemento.Renders the SelectedItemTemplate template for the item. Genera gli SelectedIndexChanging eventi SelectedIndexChanged e.Raises the SelectedIndexChanging and SelectedIndexChanged events.
Modifica"Edit" Inserisce l'elemento in modalità di modifica.Puts the item in edit mode. Esegue il rendering EditItemTemplate del modello per l'elemento.Renders the EditItemTemplate template for the item. Genera l'evento ItemEditing.Raises the ItemEditing event.
Inserire"Insert" Inserisce i valori associati dal InsertItemTemplate modello nell'origine dati.Inserts the bound values from the InsertItemTemplate template into the data source. Genera gli ItemInserting eventi ItemInserted e.Raises the ItemInserting and ItemInserted events.
Aggiornamento"Update" Aggiorna il record corrente nell'origine dati con i valori associati dal EditItemTemplate modello.Updates the current record in the data source with the bound values from the EditItemTemplate template. Genera gli ItemUpdating eventi ItemUpdated e.Raises the ItemUpdating and ItemUpdated events.
Ordinamento"Sort" Ordina le colonne elencate nella CommandArgument proprietà del pulsante.Sorts the columns listed in the CommandArgument property of the button. Genera gli Sorting eventi Sorted e.Raises the Sorting and Sorted events.

L' ItemCommand evento viene generato anche quando si fa clic su un pulsante elencato nella tabella precedente.The ItemCommand event is also raised when a button that is listed in the previous table is clicked. Tuttavia, si consiglia di utilizzare gli eventi elencati nella tabella.However, it is recommended that you use the events listed in the table. L' ItemCommand evento viene in genere utilizzato per gestire le operazioni personalizzate.The ItemCommand event is usually used to handle custom operations.

Un ListViewCommandEventArgs oggetto viene passato al gestore eventi, che consente di determinare il nome del comando e l'argomento del comando del pulsante su cui è stato fatto clic.A ListViewCommandEventArgs object is passed to the event handler, which enables you to determine the command name and command argument of the button that was clicked. Per determinare il nome del comando, utilizzare CommandEventArgs.CommandName la proprietà.To determine the command name, use the CommandEventArgs.CommandName property. Per determinare l'argomento del comando, usare CommandEventArgs.CommandArgument la proprietà.To determine the command argument, use the CommandEventArgs.CommandArgument property. Per accedere al controllo che ha generato l'evento, utilizzare ListViewCommandEventArgs.CommandSource la proprietà.To access the control that raised the event, use the ListViewCommandEventArgs.CommandSource property.

Per altre informazioni su come gestire gli eventi, vedere la gestione e generazione di eventi.For more information about how to handle events, see Handling and Raising Events.

Si applica a

Vedi anche