GridView.RowDeleting GridView.RowDeleting GridView.RowDeleting GridView.RowDeleting Event

Definición

Se produce cuando se hace clic en el botón Eliminar de una fila, pero antes de que el control GridView elimine la fila.Occurs when a row's Delete button is clicked, but before the GridView control deletes the row.

public:
 event System::Web::UI::WebControls::GridViewDeleteEventHandler ^ RowDeleting;
public event System.Web.UI.WebControls.GridViewDeleteEventHandler RowDeleting;
member this.RowDeleting : System.Web.UI.WebControls.GridViewDeleteEventHandler 
Public Custom Event RowDeleting As GridViewDeleteEventHandler 

Ejemplos

En el ejemplo siguiente se muestra cómo utilizar RowDeleting el evento para cancelar la operación de eliminación.The following example demonstrates how to use the RowDeleting event to cancel the delete operation. La página contiene un GridView control que muestra una lista de nombres y direcciones de clientes de la base de datos AdventureWorksLT.The page contains a GridView control that displays a list of customer names and addresses from the AdventureWorksLT database. Cuando el usuario hace clic en el vínculo eliminar de una fila, el controlador RowDeleting del evento comprueba el apellido de la persona mostrada en la fila que el usuario está intentando eliminar.When the user clicks the Delete link for a row, the handler for the RowDeleting event checks the last name of the person displayed in the row that the user is trying to delete. Si el apellido es "Beaver", la operación de eliminación se cancela y se muestra un mensaje de error.If the last name is "Beaver", the delete operation is canceled, and an error message is displayed. Para cualquier otro nombre, la operación de eliminación continúa y se elimina la fila.For any other name, the delete operation proceeds and the row is deleted.

El controlador RowIndex GridViewDeleteEventArgs de eventos usa la propiedad del objeto para encontrar la fila que el usuario está intentando eliminar.The event handler uses the RowIndex property of the GridViewDeleteEventArgs object to find the row that the user is trying to delete. En el ejemplo se examina el contenido de Rows la colección.The example examines the contents of the Rows collection. Si el valor que desea comparar es un valor de clave, puede examinar la DataKeys colección en su lugar.If the value you want to compare to is a key value, you could examine the DataKeys collection instead.

Las filas se eliminan de la tabla CustomerAddress en lugar de la tabla Customer para mantener el ejemplo simple.Rows are deleted from the CustomerAddress table instead of the Customer table in order to keep the example simple. El GridView control muestra el resultado de combinar tres tablas: Cliente, dirección y CustomerAddress.The GridView control shows the result of joining three tables: Customer, Address, and CustomerAddress. Cuando se elimina una fila de CustomerAddress, desaparece GridView la fila correspondiente.When a CustomerAddress row is deleted, the corresponding GridView row disappears. Las restricciones de integridad referencial harían que el código fuera un ejemplo que realmente elimina filas de la tabla Customer más compleja.Referential integrity constraints would make the code for an example that actually deletes rows from the Customer table more complex.

Para obtener información acerca de cómo configurar la base de datos AdventureWorksLT , consulte Cómo: Configure una base de datos de ejemplo AdventureWorksLTpara el desarrollo de ASP.net.For information about how to set up the AdventureWorksLT database, see How to: Set Up an AdventureWorksLT Sample Database for ASP.NET Development.


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

Comentarios

El RowDeleting evento se desencadena cuando se hace clic en el botón eliminar de una fila, pero GridView antes de que el control elimine la fila.The RowDeleting event is raised when a row's Delete button is clicked, but before the GridView control deletes the row. Esto le permite proporcionar un método de control de eventos que realiza una rutina personalizada, como cancelar la operación de eliminación, siempre que se produce este evento.This enables you to provide an event-handling method that performs a custom routine, such as canceling the delete operation, whenever this event occurs.

Un GridViewDeleteEventArgs objeto se pasa al método de control de eventos, lo que permite determinar el índice de la fila actual e indicar que se debe cancelar la operación de eliminación.A GridViewDeleteEventArgs object is passed to the event-handling method, which enables you to determine the index of the current row and to indicate that the delete operation should be canceled. Para cancelar la operación Cancel GridViewDeleteEventArgs de eliminación, establezca la propiedad del objeto en true.To cancel the delete operation, set the Cancel property of the GridViewDeleteEventArgs object to true. También puede manipular las Keys colecciones y Values , si es necesario, antes de que los valores se pasen al origen de datos.You can also manipulate the Keys and Values collections, if necessary, before the values are passed to the data source.

Para obtener más información acerca de cómo controlar eventos, vea controlar y provocar eventos.For more information about how to handle events, see Handling and Raising Events.

Se aplica a

Consulte también: