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

Definizione

Si verifica quando viene fatto clic sul pulsante Elimina di una riga, ma prima che il controllo GridView elimini la riga.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 

Esempi

Nell'esempio seguente viene illustrato come utilizzare l' RowDeleting evento per annullare l'operazione di eliminazione.The following example demonstrates how to use the RowDeleting event to cancel the delete operation. La pagina contiene un GridView controllo che visualizza un elenco di nomi e indirizzi dei clienti dal database AdventureWorksLT.The page contains a GridView control that displays a list of customer names and addresses from the AdventureWorksLT database. Quando l'utente fa clic sul collegamento Delete per una riga, il gestore per RowDeleting l'evento controlla il cognome della persona visualizzata nella riga che l'utente sta tentando di eliminare.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. Se il cognome è "Beaver", l'operazione di eliminazione viene annullata e viene visualizzato un messaggio di errore.If the last name is "Beaver", the delete operation is canceled, and an error message is displayed. Per qualsiasi altro nome, l'operazione di eliminazione continua e la riga viene eliminata.For any other name, the delete operation proceeds and the row is deleted.

Il gestore eventi utilizza la RowIndex proprietà GridViewDeleteEventArgs dell'oggetto per trovare la riga che l'utente sta tentando di eliminare.The event handler uses the RowIndex property of the GridViewDeleteEventArgs object to find the row that the user is trying to delete. Nell'esempio viene esaminato il contenuto della Rows raccolta.The example examines the contents of the Rows collection. Se il valore che si desidera confrontare è un valore chiave, è possibile esaminare la DataKeys raccolta.If the value you want to compare to is a key value, you could examine the DataKeys collection instead.

Le righe vengono eliminate dalla tabella CustomerAddress anziché dalla tabella Customer per semplificare l'esempio.Rows are deleted from the CustomerAddress table instead of the Customer table in order to keep the example simple. Il GridView controllo Mostra il risultato dell'Unione di tre tabelle: Customer, Address e CustomerAddress.The GridView control shows the result of joining three tables: Customer, Address, and CustomerAddress. Quando viene eliminata una riga CustomerAddress, la GridView riga corrispondente scompare.When a CustomerAddress row is deleted, the corresponding GridView row disappears. I vincoli di integrità referenziale comportano il codice per un esempio in cui vengono effettivamente eliminate le righe dalla tabella Customer più complesse.Referential integrity constraints would make the code for an example that actually deletes rows from the Customer table more complex.

Per informazioni su come configurare il database AdventureWorksLT, vedere procedura: Configurare un database di esempio AdventureWorksLT per lo sviluppoASP.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>

Commenti

L' RowDeleting evento viene generato quando si fa clic sul pulsante Elimina di una riga, ma prima GridView che il controllo elimini la riga.The RowDeleting event is raised when a row's Delete button is clicked, but before the GridView control deletes the row. Questo consente di fornire un metodo di gestione degli eventi che esegue una routine personalizzata, ad esempio l'annullamento dell'operazione di eliminazione, ogni volta che si verifica questo 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 oggetto viene passato al metodo di gestione degli eventi, che consente di determinare l'indice della riga corrente e di indicare che l'operazione di eliminazione deve essere annullata.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. Per annullare l'operazione di eliminazione, impostare Cancel la proprietà GridViewDeleteEventArgs dell'oggetto su true.To cancel the delete operation, set the Cancel property of the GridViewDeleteEventArgs object to true. È inoltre possibile modificare le Keys raccolte Values e, se necessario, prima che i valori vengano passati all'origine dati.You can also manipulate the Keys and Values collections, if necessary, before the values are passed to the data source.

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