DetailsViewCommandEventArgs Classe

Definição

Fornece dados para o evento de ItemCommand .

public ref class DetailsViewCommandEventArgs : System::Web::UI::WebControls::CommandEventArgs
public class DetailsViewCommandEventArgs : System.Web.UI.WebControls.CommandEventArgs
type DetailsViewCommandEventArgs = class
    inherit CommandEventArgs
Public Class DetailsViewCommandEventArgs
Inherits CommandEventArgs
Herança
DetailsViewCommandEventArgs

Exemplos

O exemplo de código a seguir demonstra como usar o DetailsViewCommandEventArgs objeto passado para o manipulador de eventos do ItemCommand evento para determinar o nome do comando do botão clicado pelo usuário. Este exemplo usa o modelo de codificação de arquivo único.


<%@ 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 ItemDetailsView_ItemCommand(Object sender, 
      DetailsViewCommandEventArgs e)
  {

    // Use the CommandName property to determine which button
    // was clicked. 
    if (e.CommandName == "Add")
    {

      // Add the customer to the customer list. 

      // Get the row that contains the company name. In this
      // example, the company name is in the second row (index 1)  
      // of the DetailsView control.
      DetailsViewRow row = ItemDetailsView.Rows[1];

      // Get the company's name from the appropriate cell.
      // In this example, the company name is in the second cell  
      // (index 1) of the row.
      String name = row.Cells[1].Text;

      // Create a ListItem object with the company name.
      ListItem item = new ListItem(name);

      // Add the ListItem object to the ListBox control, if the 
      // item does not already exist.
      if (!CustomerListBox.Items.Contains(item))
      {
        CustomerListBox.Items.Add(item);
      }

    }

  }
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>DetailsViewCommandEventArgs Example</title>
</head>
<body>
    <form id="form1" runat="server">
    
      <h3>DetailsViewCommandEventArgs Example</h3>
  
      <asp:detailsview id="ItemDetailsView"
        datasourceid="DetailsViewSource"
        allowpaging="true"
        autogeneraterows="false" 
        onitemcommand="ItemDetailsView_ItemCommand"  
        runat="server">
        <fields>
          <asp:boundfield datafield="CustomerID"
            headertext="Customer ID"/>
          <asp:boundfield datafield="CompanyName"
            headertext="Company Name"/>
          <asp:boundfield datafield="Address"
            headertext="Address"/>
          <asp:boundfield datafield="City"
            headertext="City"/>
          <asp:boundfield datafield="PostalCode"
            headertext="ZIP Code"/>
          <asp:boundfield datafield="Country"
            headertext="Country"/>
          <asp:buttonfield buttontype="Link"
            causesvalidation="false"
            text="Add to List"
            commandname="Add"/>
        </fields>
      </asp:detailsview>
      
      <br/><br/>
      
      Selected Customers:<br/>
      <asp:listbox id="CustomerListBox"
        runat="server"/>
      
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="DetailsViewSource"
        selectcommand="Select [CustomerID], [CompanyName], [Address], 
          [City], [PostalCode], [Country] From [Customers]"
        connectionstring=
            "<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>  
  
    </form>
  </body>
</html>

<%@ page language="VB" autoeventwireup="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
  
  Sub ItemDetailsView_ItemCommand(ByVal sender As Object, _
    ByVal e As DetailsViewCommandEventArgs) _
    Handles ItemDetailsView.ItemCommand

    ' Use the CommandName property to determine which button
    ' was clicked. 
    If e.CommandName = "Add" Then

      ' Add the customer to the customer list. 

      ' Get the row that contains the company name. In this
      ' example, the company name is in the second row (index 1)  
      ' of the DetailsView control.
      Dim row As DetailsViewRow = ItemDetailsView.Rows(1)

      ' Get the company's name from the appropriate cell.
      ' In this example, the company name is in the second cell  
      ' (index 1) of the row.
      Dim name As String = row.Cells(1).Text

      ' Create a ListItem object with the company name.
      Dim item As New ListItem(name)

      ' Add the ListItem object to the ListBox control, if the 
      ' item does not already exist.
      If Not CustomerListBox.Items.Contains(item) Then

        CustomerListBox.Items.Add(item)
        
      End If

    End If

  End Sub
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>DetailsViewCommandEventArgs Example</title>
</head>
<body>
    <form id="form1" runat="server">
    
      <h3>DetailsViewCommandEventArgs Example</h3>
  
      <asp:detailsview id="ItemDetailsView"
        datasourceid="DetailsViewSource"
        allowpaging="true"
        autogeneraterows="false"  
        runat="server">
        <fields>
          <asp:boundfield datafield="CustomerID"
            headertext="Customer ID"/>
          <asp:boundfield datafield="CompanyName"
            headertext="Company Name"/>
          <asp:boundfield datafield="Address"
            headertext="Address"/>
          <asp:boundfield datafield="City"
            headertext="City"/>
          <asp:boundfield datafield="PostalCode"
            headertext="ZIP Code"/>
          <asp:boundfield datafield="Country"
            headertext="Country"/>
          <asp:buttonfield buttontype="Link"
            causesvalidation="false"
            text="Add to List"
            commandname="Add"/>
        </fields>
      </asp:detailsview>
      
      <br/><br/>
      
      Selected Customers:<br/>
      <asp:listbox id="CustomerListBox"
        runat="server"/>
      
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="DetailsViewSource"
        selectcommand="Select [CustomerID], [CompanyName], [Address], 
          [City], [PostalCode], [Country] From [Customers]"
        connectionstring=
            "<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>  
  
    </form>
  </body>
</html>

O exemplo de código a seguir mostra uma versão do modelo de codificação code-behind do exemplo anterior. Para que este exemplo funcione, você deve copiar o código abaixo para o arquivo code-behind associado.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>DetailsViewCommandEventArgs Example</title>
</head>
<body>
    <form id="Form1" runat="server">
    
      <h3>DetailsViewCommandEventArgs Example</h3>
  
      <asp:detailsview id="ItemDetailsView"
        datasourceid="DetailsViewSource"
        allowpaging="true"
        autogeneraterows="false" 
        onitemcommand="ItemDetailsView_ItemCommand"  
        runat="server">
        <fields>
          <asp:boundfield datafield="CustomerID"
            headertext="Customer ID"/>
          <asp:boundfield datafield="CompanyName"
            headertext="Company Name"/>
          <asp:boundfield datafield="Address"
            headertext="Address"/>
          <asp:boundfield datafield="City"
            headertext="City"/>
          <asp:boundfield datafield="PostalCode"
            headertext="ZIP Code"/>
          <asp:boundfield datafield="Country"
            headertext="Country"/>
          <asp:buttonfield buttontype="Link"
            causesvalidation="false"
            text="Add to List"
            commandname="Add"/>
        </fields>
      </asp:detailsview>
      
      <br/><br/>
      
      Selected Customers:<br/>
      <asp:listbox id="CustomerListBox"
        runat="server"/>
      
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="DetailsViewSource"
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>  
  
    </form>
  </body>
</html>
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="DefaultVB.aspx.vb" Inherits="DefaultVB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>DetailsViewCommandEventArgs Example</title>
</head>
<body>
    <form id="Form1" runat="server">
    
      <h3>DetailsViewCommandEventArgs Example</h3>
  
      <asp:detailsview id="ItemDetailsView"
        datasourceid="DetailsViewSource"
        allowpaging="true"
        autogeneraterows="false" 
        onitemcommand="ItemDetailsView_ItemCommand"  
        runat="server">
        <fields>
          <asp:boundfield datafield="CustomerID"
            headertext="Customer ID"/>
          <asp:boundfield datafield="CompanyName"
            headertext="Company Name"/>
          <asp:boundfield datafield="Address"
            headertext="Address"/>
          <asp:boundfield datafield="City"
            headertext="City"/>
          <asp:boundfield datafield="PostalCode"
            headertext="ZIP Code"/>
          <asp:boundfield datafield="Country"
            headertext="Country"/>
          <asp:buttonfield buttontype="Link"
            causesvalidation="false"
            text="Add to List"
            commandname="Add"/>
        </fields>
      </asp:detailsview>
      
      <br/><br/>
      
      Selected Customers:<br/>
      <asp:listbox id="CustomerListBox"
        runat="server"/>
      
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="DetailsViewSource"
        selectcommand="Select [CustomerID], [CompanyName], [Address], 
          [City], [PostalCode], [Country] From [Customers]"
        connectionstring=
          "<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>  
  
    </form>
  </body>
</html>

O exemplo de código a seguir mostra o arquivo code-behind do exemplo anterior.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    public void ItemDetailsView_ItemCommand(Object sender, DetailsViewCommandEventArgs e)
    {

        // Use the CommandName property to determine which button
        // was clicked. 
        if (e.CommandName == "Add")
        {

            // Add the customer to the customer list. 

            // Get the row that contains the company name. In this
            // example, the company name is in the second row (index 1)  
            // of the DetailsView control.
            DetailsViewRow row = ItemDetailsView.Rows[1];

            // Get the company's name from the appropriate cell.
            // In this example, the company name is in the second cell  
            // (index 1) of the row.
            String name = row.Cells[1].Text;

            // Create a ListItem object with the company name.
            ListItem item = new ListItem(name);

            // Add the ListItem object to the ListBox control, if the 
            // item does not already exist.
            if (!CustomerListBox.Items.Contains(item))
            {
                CustomerListBox.Items.Add(item);
            }
        }
    }
}
Partial Class DefaultVB
    Inherits System.Web.UI.Page

    Public Sub ItemDetailsView_ItemCommand(ByVal sender As Object, ByVal e As DetailsViewCommandEventArgs)
        ' Use the CommandName property to determine which button
        ' was clicked. 
        If e.CommandName = "Add" Then
        
            ' Add the customer to the customer list. 

            ' Get the row that contains the company name. In this
            ' example, the company name is in the second row (index 1)  
            ' of the DetailsView control.
            Dim row As DetailsViewRow = ItemDetailsView.Rows(1)

            ' Get the company's name from the appropriate cell.
            ' In this example, the company name is in the second cell  
            ' (index 1) of the row.
            Dim name As String = row.Cells(1).Text

            ' Create a ListItem object with the company name.
            Dim item As ListItem = New ListItem(name)

            ' Add the ListItem object to the ListBox control, if the 
            ' item does not already exist.
            If Not CustomerListBox.Items.Contains(item) Then
                CustomerListBox.Items.Add(item)
            End If
        End If
    End Sub

End Class

Comentários

O DetailsView controle aciona o ItemCommand evento quando um botão dentro de um ButtonFieldcampo de linha , CommandFieldou TemplateField é clicado. Isso permite que você forneça um manipulador de eventos que executa uma rotina personalizada sempre que esse evento ocorre.

Observação

O DetailsView controle também gera outros eventos especializados quando determinados botões são clicados (botões com a CommandName propriedade definida como "Excluir", "Inserir", "Página" ou "Atualizar"). Ao usar um desses botões, você deve considerar o uso de um dos eventos especializados fornecidos pelo controle (como ItemDeleted ou ItemDeleting).

Um DetailsViewCommandEventArgs objeto é passado para o manipulador de eventos. Se o botão que gerou o evento tiver um nome de comando ou valor de argumento de comando, você poderá usar o DetailsViewCommandEventArgs objeto para determinar esses valores. Para determinar o nome do comando e o argumento de comando do botão clicado, use as CommandName propriedades e CommandArgument , respectivamente. Você também pode acessar o DetailsView controle que gerou o evento usando a CommandSource propriedade .

Para obter uma lista de valores de propriedade iniciais para uma instância da DetailsViewCommandEventArgs classe , consulte o DetailsViewCommandEventArgs construtor .

Construtores

DetailsViewCommandEventArgs(Object, CommandEventArgs)

Inicializa uma nova instância da classe DetailsViewCommandEventArgs.

Propriedades

CommandArgument

Obtém o argumento para o comando.

(Herdado de CommandEventArgs)
CommandName

Obtém o nome do comando.

(Herdado de CommandEventArgs)
CommandSource

Obtém a fonte do comando.

Handled

Obtém ou define um valor que indica se o controle manipulou o evento.

Métodos

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Aplica-se a

Confira também