SqlDataSource.Delete Método

Definición

Realiza una operación de eliminación mediante la cadena SQL DeleteCommand SQL y cualquier parámetro que esté en la colección DeleteParameters.Performs a delete operation using the DeleteCommand SQL string and any parameters that are in the DeleteParameters collection.

public:
 int Delete();
public int Delete ();
member this.Delete : unit -> int
Public Function Delete () As Integer

Devoluciones

Int32

Valor que representa el número de filas eliminadas de la base de datos subyacente.A value that represents the number of rows deleted from the underlying database.

Excepciones

El control SqlDataSource no puede establecer una conexión con el origen de datos subyacente.The SqlDataSource cannot establish a connection with the underlying data source.

Ejemplos

En el ejemplo de código siguiente se muestra cómo establecer el DeleteCommand texto para eliminar un pedido de la base de datos Northwind.The following code example demonstrates how to set the DeleteCommand text to delete an order from the Northwind database. Inicialmente, los datos se recuperan de la tabla Orders y se muestran en un DropDownList control.Initially, data is retrieved from the Orders table and displayed in a DropDownList control. Debe declarar explícitamente la DeleteParameters propiedad y llamar al Delete método al utilizar controles enlazados a datos, como DropDownList (a diferencia de otros controles, como GridView y DetailsView , que rellenan automáticamente los parámetros y llaman al Delete método en un control de origen de datos).You must explicitly declare the DeleteParameters property and call the Delete method when using data-bound controls, such as the DropDownList (unlike other controls, such as GridView and DetailsView, which automatically populate the parameters and call the Delete method on a data source control). En este ejemplo, el OnClick evento se delega en el OnDelete controlador de eventos privado, que llama explícitamente al Delete método del SqlDataSource control.In this example, the OnClick event is delegated to the private OnDelete event handler, which explicitly calls the Delete method of the SqlDataSource control.

<%@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">
private void OnDelete(Object sender, EventArgs e) {
    SqlDataSource1.Delete();
}
</script>

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

            <asp:SqlDataSource
                id="SqlDataSource1"
                runat="server"
                ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
                SelectCommand="SELECT OrderID FROM Orders"
                DeleteCommand="DELETE FROM [Order Details] WHERE OrderID=@OrderID;DELETE FROM Orders WHERE OrderID=@OrderID;">
                <DeleteParameters>
                    <asp:ControlParameter Name="OrderID" ControlId="DropDownList1" PropertyName="SelectedValue" />
                </DeleteParameters>
            </asp:SqlDataSource>

            <asp:DropDownList
                id="DropDownList1"
                runat="server"
                DataTextField="OrderID"
                DataValueField="OrderID"
                DataSourceID="SqlDataSource1">
            </asp:DropDownList>

            <asp:Button
                id="Button1"
                runat="server"
                Text="Delete Order"
                OnClick="OnDelete">
            </asp:Button>

        </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 On_Delete(ByVal sender As Object, ByVal e As EventArgs)
    SqlDataSource1.Delete()
 End Sub 'On_Delete
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
    <title>ASP.NET Example</title>
</head>

    <body>
        <form id="form1" runat="server">

            <asp:SqlDataSource
                id="SqlDataSource1"
                runat="server"
                ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
                SelectCommand="SELECT OrderID FROM Orders"
                DeleteCommand="DELETE FROM [Order Details] WHERE OrderID=@OrderID;DELETE FROM Orders WHERE OrderID=@OrderID;">
                <DeleteParameters>
                    <asp:ControlParameter Name="OrderID" ControlId="DropDownList1" PropertyName="SelectedValue" />
                </DeleteParameters>
            </asp:SqlDataSource>

            <asp:DropDownList
                id="DropDownList1"
                runat="server"
                DataTextField="OrderID"
                DataValueField="OrderID"
                DataSourceID="SqlDataSource1">
            </asp:DropDownList>

            <asp:Button
                id="Button1"
                runat="server"
                Text="Delete Order"
                OnClick="On_Delete">
            </asp:Button>

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

Comentarios

Antes de que se realice la operación de eliminación, OnDeleting se llama al método para generar el Deleting evento.Before the delete operation is performed, the OnDeleting method is called to raise the Deleting event. Puede controlar este evento para examinar los valores de los parámetros y realizar cualquier preprocesamiento antes de una operación de eliminación.You can handle this event to examine the values of the parameters and to perform any preprocessing before a delete operation.

Una vez finalizada la operación, OnDeleted se llama al método para generar el Deleted evento.After the operation completes, the OnDeleted method is called to raise the Deleted event. Puede controlar este evento para examinar los valores devueltos y los códigos de error, así como para realizar cualquier procesamiento posterior.You can handle this event to examine any return values and error codes and to perform any post-processing.

El Delete método se proporciona para el acceso mediante programación al Delete método.The Delete method is provided for programmatic access to the Delete method. Si el SqlDataSource control está asociado a un control enlazado a datos, el control enlazado a datos llama automáticamente al método Delete .If the SqlDataSource control is associated with a data-bound control, the data-bound control automatically calls the Delete method.

El Delete método delega en el Delete método del SqlDataSourceView objeto que está asociado al SqlDataSource control.The Delete method delegates to the Delete method of the SqlDataSourceView object that is associated with the SqlDataSource control. Para realizar la operación, SqlDataSourceView crea un DbCommand objeto utilizando el DeleteCommand texto y los valores asociados DeleteParameters y, a continuación, ejecuta DbCommand en la base de datos subyacente.To perform the operation, the SqlDataSourceView builds a DbCommand object using the DeleteCommand text and any associated DeleteParameters values, and then executes the DbCommand against the underlying database.

Se aplica a

Consulte también