Partilhar via


GridViewDeleteEventHandler Delegar

Definição

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

public delegate void GridViewDeleteEventHandler(System::Object ^ sender, GridViewDeleteEventArgs ^ e);
public delegate void GridViewDeleteEventHandler(object sender, GridViewDeleteEventArgs e);
type GridViewDeleteEventHandler = delegate of obj * GridViewDeleteEventArgs -> unit
Public Delegate Sub GridViewDeleteEventHandler(sender As Object, e As GridViewDeleteEventArgs)

Parâmetros

sender
Object

A fonte do evento.

e
GridViewDeleteEventArgs

Um objeto de GridViewDeleteEventArgs que contém os dados do evento.

Exemplos

O exemplo a seguir demonstra como adicionar programaticamente um GridViewDeleteEventHandler delegado ao RowDeleting 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>

<%@ 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 Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            
    ' Create a new GridView control.
    Dim customersGridView As New GridView()
         
    ' Set the GridView control's properties.          
    customersGridView.ID = "CustomersGridView"
    customersGridView.DataSourceID = "CustomersSqlDataSource"
    customersGridView.AutoGenerateColumns = True
    customersGridView.AutoGenerateDeleteButton = True
    Dim keyArray() As String = {"CustomerID"}
    customersGridView.DataKeyNames = keyArray
       
    ' Programmatically register the event-handling methods.
    AddHandler customersGridView.RowDeleting, AddressOf CustomersGridView_RowDeleting
        
    ' Add the GridView object to the Controls collection
    ' of the PlaceHolder control.
    GridViewPlaceHolder.Controls.Add(customersGridView)
        
  End Sub
    
  Sub CustomersGridView_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)

    ' User the sender parameter to retrieve the GridView control
    ' that raised the event.
    Dim customersGridView As GridView = CType(sender, GridView)
    
    ' Cancel the delete operation if the user attempts to remove
    ' the last record from the GridView control.
    If customersGridView.Rows.Count <= 1 Then

      e.Cancel = True
      Message.Text = "You must keep at least one record."
            
    End If
    
  End Sub

</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 adicionar declarativamente um GridViewDeleteEventHandler delegado ao RowDeleting 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>

<%@ 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">

    Private Sub CustomersGridView_RowDeleting _
        (ByVal sender As [Object], _
        ByVal e As GridViewDeleteEventArgs)
        Dim cell As TableCell
        cell = CustomersGridView.Rows(e.RowIndex).Cells(2)
        If cell.Text = "Beaver" Then
            e.Cancel = True
            Message.Text = "You cannot delete customer Beaver."
        Else
            Message.Text = ""
        End If
    End Sub
    
</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>

Comentários

O GridView controle aciona o RowDeleting evento quando um botão Excluir (um botão com sua CommandName propriedade definida como "Excluir") é clicado, mas antes que o GridView controle exclua o registro. Isso permite que você forneça um método de manipulação de eventos que executa uma rotina personalizada, como cancelar a operação de exclusão, sempre que esse evento ocorrer.

Ao criar um GridViewDeleteEventHandler delegado, você identifica o método que manipulará o evento. Para associar o evento ao manipulador de eventos, adicione uma instância do delegado ao evento. O manipulador de eventos é chamado sempre que o evento ocorre, a menos que você remova o representante. Para obter mais informações sobre delegados do manipulador de eventos, consulte Manipulando e gerando eventos.

Métodos de Extensão

GetMethodInfo(Delegate)

Obtém um objeto que representa o método representado pelo delegado especificado.

Aplica-se a

Confira também