GridView.RowDeleting Evento
Definição
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
Tipo de evento
Exemplos
O exemplo a seguir demonstra como usar o RowDeleting evento para cancelar a operação de exclusão.The following example demonstrates how to use the RowDeleting event to cancel the delete operation. A página contém um GridView controle que exibe uma lista de nomes de clientes e endereços do banco de dados AdventureWorksLT.The page contains a GridView control that displays a list of customer names and addresses from the AdventureWorksLT database. Quando o usuário clica no link excluir para uma linha, o manipulador do RowDeleting evento verifica o sobrenome da pessoa exibida na linha que o usuário está tentando excluir.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 o sobrenome for "Beaver", a operação de exclusão será cancelada e uma mensagem de erro será exibida.If the last name is "Beaver", the delete operation is canceled, and an error message is displayed. Para qualquer outro nome, a operação de exclusão continua e a linha é excluída.For any other name, the delete operation proceeds and the row is deleted.
O manipulador de eventos usa a RowIndex Propriedade do GridViewDeleteEventArgs objeto para localizar a linha que o usuário está tentando excluir.The event handler uses the RowIndex property of the GridViewDeleteEventArgs object to find the row that the user is trying to delete. O exemplo examina o conteúdo da Rows coleção.The example examines the contents of the Rows collection. Se o valor que você deseja comparar for um valor de chave, você poderá examinar a DataKeys coleção em vez disso.If the value you want to compare to is a key value, you could examine the DataKeys collection instead.
As linhas são excluídas da tabela CustomerAddress em vez da tabela Customer para manter o exemplo simples.Rows are deleted from the CustomerAddress table instead of the Customer table in order to keep the example simple. O GridView controle mostra o resultado da junção de três tabelas: Customer, address e CustomerAddress.The GridView control shows the result of joining three tables: Customer, Address, and CustomerAddress. Quando uma linha CustomerAddress é excluída, a GridView linha correspondente desaparece.When a CustomerAddress row is deleted, the corresponding GridView row disappears. As restrições de integridade referencial tornaria o código um exemplo que realmente exclui linhas da tabela Customer mais complexas.Referential integrity constraints would make the code for an example that actually deletes rows from the Customer table more complex.
Para obter informações sobre como configurar o banco de dados AdventureWorksLT, consulte como: configurar um banco de dados de exemplo AdventureWorksLT para desenvolvimento 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>
Comentários
O RowDeleting evento é gerado quando um botão de exclusão de uma linha é clicado, mas antes de o GridView controle excluir a linha.The RowDeleting event is raised when a row's Delete button is clicked, but before the GridView control deletes the row. 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.This enables you to provide an event-handling method that performs a custom routine, such as canceling the delete operation, whenever this event occurs.
Um GridViewDeleteEventArgs objeto é passado para o método de manipulação de eventos, que permite que você determine o índice da linha atual e indique que a operação de exclusão deve ser cancelada.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 a operação de exclusão, defina a Cancel Propriedade do GridViewDeleteEventArgs objeto como true .To cancel the delete operation, set the Cancel property of the GridViewDeleteEventArgs object to true. Você também pode manipular as Keys Values coleções e, se necessário, antes que os valores sejam passados para a fonte de dados.You can also manipulate the Keys and Values collections, if necessary, before the values are passed to the data source.
Para obter mais informações sobre como lidar com eventos, consulte manipulando e gerando eventos.For more information about how to handle events, see Handling and Raising Events.