Exportar (0) Imprimir
Expandir Tudo
Expandir Minimizar
Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações.
Tradução
Original

Delegado GridViewDeleteEventHandler

Representa o método que manipula o RowDeleting o evento de um GridView controle.

Namespace:  System.Web.UI.WebControls
Assembly:  System.Web (em System.Web.dll)

public delegate void GridViewDeleteEventHandler(
	Object sender,
	GridViewDeleteEventArgs e
)

Parâmetros

sender
Tipo: System.Object
A origem do evento.
e
Tipo: System.Web.UI.WebControls.GridViewDeleteEventArgs
A GridViewDeleteEventArgs objeto que contém os dados do evento.

O GridView controlar gera a RowDeleting evento quando um botão Excluir (um botão com sua CommandName propriedade definida como 'Delete') for clicado, mas antes o GridView controle exclui o registro. Isso permite que você fornecer um método de manipulação de eventos que executa uma rotina personalizada, tais como cancelar a operação de exclusão, sempre que esse evento ocorre.

Quando você cria um GridViewDeleteEventHandler representante, você identifica o método que manipulará o evento. Para associar o evento com o manipulador de eventos, adicione uma instância do delegate ao evento. O manipulador de evento é chamado sempre que o evento ocorre, a menos que você remova o delegate. Para obter mais informações sobre delegates de manipulador de eventos, consulte Eventos e representantes.

O exemplo a seguir demonstra como programaticamente adicionar um GridViewDeleteEventHandler delegar para o RowDeleting o evento de um GridView controle.



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

    // Create a new GridView control.
    GridView customersGridView = new GridView();

    // Set the GridView control's properties.          
    customersGridView.ID = "CustomersGridView";
    customersGridView.DataSourceID = "CustomersSqlDataSource"; 
    customersGridView.AutoGenerateColumns = true;
    customersGridView.AutoGenerateDeleteButton = true;
    customersGridView.DataKeyNames = new String[] {"CustomerID"};

    // Programmatically register the event-handling methods.
    customersGridView.RowDeleting += new GridViewDeleteEventHandler(this.CustomersGridView_RowDeleting);

    // Add the GridView object to the Controls collection
    // of the PlaceHolder control.
    GridViewPlaceHolder.Controls.Add(customersGridView);

  }

  void CustomersGridView_RowDeleting(Object sender, GridViewDeleteEventArgs e)
  {

    // User the sender parameter to retrieve the GridView control
    // that raised the event.
    GridView customersGridView = (GridView)sender;

    // Cancel the delete operation if the user attempts to remove
    // the last record from the GridView control.
    if (customersGridView.Rows.Count <= 1)
    {

      e.Cancel = true;
      Message.Text = "You must keep at least one record.";

    }

  }  

</script>

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

      <h3>GridViewDeleteEventHandler Example</h3>

      <asp:label id="Message"
        forecolor="Red"          
        runat="server"/>

      <br/>

      <asp:placeholder id="GridViewPlaceHolder"
        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="CustomersSqlDataSource"  
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        deletecommand="Delete from Customers where CustomerID = @CustomerID"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
        runat="server">
      </asp:sqldatasource>

    </form>
  </body>
</html>



O exemplo a seguir demonstra como declarativamente adicionar um GridViewDeleteEventHandler delegar para o RowDeleting o evento de um GridView controle.



<%@ 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_RowDeleting
        (Object sender, GridViewDeleteEventArgs e)
    {
        TableCell cell = CustomersGridView.Rows[e.RowIndex].Cells[2];
        if (cell.Text == "Beaver")
        {
            e.Cancel = true;
            Message.Text = "You cannot delete customer Beaver.";
        }
        else
        {
            Message.Text = "";
        }
    }  

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>GridView RowDeleting Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <h3>
        GridView RowDeleting Example
    </h3>
    <asp:Label ID="Message" ForeColor="Red" runat="server" />
    <br />
    <asp:GridView ID="CustomersGridView" runat="server" 
        DataSourceID="CustomersSqlDataSource" 
        AutoGenerateColumns="False"
        AutoGenerateDeleteButton="True" 
        OnRowDeleting="CustomersGridView_RowDeleting"
        DataKeyNames="CustomerID,AddressID">
        <Columns>
            <asp:BoundField DataField="FirstName" 
                HeaderText="FirstName" SortExpression="FirstName" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" 
                SortExpression="LastName" />
            <asp:BoundField DataField="City" HeaderText="City" 
                SortExpression="City" />
            <asp:BoundField DataField="StateProvince" HeaderText="State" 
                SortExpression="StateProvince" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="CustomersSqlDataSource" runat="server"
        SelectCommand="SELECT SalesLT.CustomerAddress.CustomerID, 
            SalesLT.CustomerAddress.AddressID, 
            SalesLT.Customer.FirstName, 
            SalesLT.Customer.LastName, 
            SalesLT.Address.City, 
            SalesLT.Address.StateProvince 
            FROM SalesLT.Customer 
            INNER JOIN SalesLT.CustomerAddress 
            ON SalesLT.Customer.CustomerID = 
                SalesLT.CustomerAddress.CustomerID 
            INNER JOIN SalesLT.Address ON SalesLT.CustomerAddress.AddressID = 
                SalesLT.Address.AddressID"
        DeleteCommand="Delete from SalesLT.CustomerAddress where CustomerID = 
            @CustomerID and AddressID = @AddressID" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorksLTConnectionString %>">
        <DeleteParameters>
            <asp:Parameter Name="AddressID" />
            <asp:Parameter Name="CustomerID" />
        </DeleteParameters>
    </asp:SqlDataSource>
    </form>
</body>
</html>


.NET Framework

Com suporte em: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Função Server Core sem suporte), Windows Server 2008 R2 (Função Server Core com suporte com o SP1 ou posterior, Itanium sem suporte)

O .NET Framework não oferece suporte a todas as versões de cada plataforma. Para obter uma lista das versões com suporte, consulte Requisitos do sistema do .NET Framework.

Contribuições da comunidade

ADICIONAR
Mostrar:
© 2014 Microsoft