DetailsViewDeletedEventHandler Делегат

Определение

Представляет метод, обрабатывающий событие ItemDeleted элемента управления DetailsView.

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

Параметры

sender
Object

Источник события.

e
DetailsViewDeletedEventArgs

Объект DetailsViewDeletedEventArgs, содержащий данные события.

Примеры

В следующем примере кода показано, как программно добавить DetailsViewDeletedEventHandler делегат в ItemDeleted событие DetailsView элемента управления .


<%@ page language="C#"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  
  <script runat="server">
  
    void Page_Load(Object sender, EventArgs e)
    {
      
      // Create a new DetailsView object.
      DetailsView customerDetailsView = new DetailsView();
      
      // Set the DetailsView object's properties.
      customerDetailsView.ID = "CustomerDetailsView";
      customerDetailsView.DataSourceID = "DetailsViewSource";
      customerDetailsView.AutoGenerateRows = true;
      customerDetailsView.AutoGenerateDeleteButton = true;
      customerDetailsView.AllowPaging = true;
      customerDetailsView.PagerSettings.Mode = 
        PagerButtons.NextPrevious;
      customerDetailsView.DataKeyNames = new String[1] { "CustomerID" };

      // Programmatically register the event-handling method
      // for the ItemDeleted event of a DetailsView control.
      customerDetailsView.ItemDeleted += 
        new DetailsViewDeletedEventHandler(
        this.CustomerDetailView_ItemDeleted);

      // Add the DetailsView object to the Controls collection
      // of the PlaceHolder control.
      DetailsViewPlaceHolder.Controls.Add(customerDetailsView);

    }

    void CustomerDetailView_ItemDeleted(Object sender, 
      DetailsViewDeletedEventArgs e)
    {
      // Use the Exception property to determine whether an exception
      // occurred during the delete operation.
      if (e.Exception == null)
      {
        // Use the AffectedRows property to determine the numbers of
        // rows affected by the delete operation.
        if (e.AffectedRows == 1)
        {
          MessageLabel.Text = e.AffectedRows.ToString() 
            + " record deleted successfully.";
        }
        else
        {
          MessageLabel.Text = e.AffectedRows.ToString() 
            + " records deleted successfully.";
        }
      }
      else
      {
        // Insert the code to handle the exception.
        MessageLabel.Text = e.Exception.Message;

        // Use the ExceptionHandled property to indicate that the 
        // exception is already handled.
        e.ExceptionHandled = true;
      }
    }
  
  </script>
    
  <head runat="server">
    <title>DetailsViewDeletedEventHandler Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>DetailsViewDeletedEventHandler Example</h3>
        
        <!-- Use a PlaceHolder control as the container for the -->
        <!-- dynamically generated DetailsView control.         -->       
        <asp:PlaceHolder id="DetailsViewPlaceHolder"
          runat="server"/>
          
        <br/><br/>
        
        <asp:label id="MessageLabel"
          forecolor="Red"
          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="DetailsViewSource"
          selectcommand="Select [CustomerID], [CompanyName], [Address], 
            [City], [PostalCode], [Country] From [Customers]"
          deletecommand="Delete [Customers] 
            Where [CustomerID]=@CustomerID"
          connectionstring=
            "<%$ ConnectionStrings:NorthWindConnectionString%>" 
          runat="server"/>
            
      </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">
<html xmlns="http://www.w3.org/1999/xhtml" >
  
  <script runat="server">
  
    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      
      ' Create a new DetailsView object.
      Dim customerDetailsView As New DetailsView()
      
      ' Set the DetailsView object's properties.
      customerDetailsView.ID = "CustomerDetailsView"
      customerDetailsView.DataSourceID = "DetailsViewSource"
      customerDetailsView.AutoGenerateRows = True
      customerDetailsView.AutoGenerateDeleteButton = True
      customerDetailsView.AllowPaging = True
      customerDetailsView.PagerSettings.Mode = _
        PagerButtons.NextPrevious
      
      Dim keyArray() As String = {"CustomerID"}
      customerDetailsView.DataKeyNames = keyArray

      ' Programmatically register the event-handling method
      ' for the ItemDeleted event of a DetailsView control.
      AddHandler customerDetailsView.ItemDeleted, _
        AddressOf CustomerDetailView_ItemDeleted

      ' Add the DetailsView object to the Controls collection
      ' of the PlaceHolder control.
      DetailsViewPlaceHolder.Controls.Add(customerDetailsView)

    End Sub

    Sub CustomerDetailView_ItemDeleted(ByVal sender As Object, _
      ByVal e As DetailsViewDeletedEventArgs)
  
      ' Use the Exception property to determine whether an exception
      ' occurred during the delete operation.
      If e.Exception Is Nothing Then
    
        ' Use the AffectedRows property to determine the numbers of
        ' rows affected by the delete operation.
        If e.AffectedRows = 1 Then
      
          MessageLabel.Text = e.AffectedRows.ToString() _
            & " record deleted successfully."
      
        Else
              
          MessageLabel.Text = e.AffectedRows.ToString() _
            & " records deleted successfully."
      
        End If
    
      Else
    
        ' Insert the code to handle the exception.
        MessageLabel.Text = e.Exception.Message
      
        ' Use the ExceptionHandled property to indicate that the 
        ' exception is already handled.
        e.ExceptionHandled = True
    
      End If
    
    End Sub
  
  </script>
    
  <head runat="server">
    <title>DetailsViewDeletedEventHandler Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>DetailsViewDeletedEventHandler Example</h3>
        
        <!-- Use a PlaceHolder control as the container for the -->
        <!-- dynamically generated DetailsView control.         -->       
        <asp:PlaceHolder id="DetailsViewPlaceHolder"
          runat="server"/>
          
        <br/><br/>
        
        <asp:label id="MessageLabel"
          forecolor="Red"
          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="DetailsViewSource"
          selectcommand="Select [CustomerID], [CompanyName], [Address], 
            [City], [PostalCode], [Country] From [Customers]"
          deletecommand="Delete [Customers] 
            Where [CustomerID]=@CustomerID"
          connectionstring=
            "<%$ ConnectionStrings:NorthWindConnectionString%>" 
          runat="server"/>
            
      </form>
  </body>
</html>

В следующем примере кода показано, как декларативно добавить DetailsViewDeletedEventHandler делегат в ItemDeleted событие DetailsView элемента управления .


<%@ page language="C#"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  
  <script runat="server">

    void CustomerDetailView_ItemDeleted(Object sender, 
      DetailsViewDeletedEventArgs e)
    {
      // Use the Exception property to determine whether an exception
      // occurred during the delete operation.
      if (e.Exception == null)
      {
        // Use the AffectedRows property to determine the numbers of
        // rows affected by the delete operation.
        if (e.AffectedRows == 1)
        {
          MessageLabel.Text = e.AffectedRows.ToString() 
            + " record deleted successfully.";
        }
        else
        {
          MessageLabel.Text = e.AffectedRows.ToString() 
            + " records deleted successfully.";
        }
      }
      else
      {
        // Insert the code to handle the exception.
        MessageLabel.Text = e.Exception.Message;

        // Use the ExceptionHandled property to indicate that the 
        // exception is already handled.
        e.ExceptionHandled = true;
      }
    }
  
  </script>
    
  <head runat="server">
    <title>DetailsViewDeletedEventHandler Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>DetailsViewDeletedEventHandler Example</h3>
        
        <asp:detailsview id="CustomerDetailsView"
          datasourceid="DetailsViewSource"
          autogeneraterows="true"
          autogeneratedeletebutton="true"
          allowpaging="true"
          datakeynames="CustomerID" 
          runat="server">
        
          <pagersettings mode="NextPrevious"/>
        
        </asp:detailsview>
          
        <br/><br/>
        
        <asp:label id="MessageLabel"
          forecolor="Red"
          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="DetailsViewSource"
          selectcommand="Select [CustomerID], [CompanyName], [Address], 
            [City], [PostalCode], [Country] From [Customers]"
          deletecommand="Delete [Customers] 
            Where [CustomerID]=@CustomerID"
          connectionstring=
            "<%$ ConnectionStrings:NorthWindConnectionString%>" 
          runat="server"/>
            
      </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">
<html xmlns="http://www.w3.org/1999/xhtml" >
  
  <script runat="server">

    Sub CustomerDetailView_ItemDeleted(ByVal sender As Object, _
      ByVal e As DetailsViewDeletedEventArgs)
  
      ' Use the Exception property to determine whether an exception
      ' occurred during the delete operation.
      If e.Exception Is Nothing Then
    
        ' Use the AffectedRows property to determine the numbers of
        ' rows affected by the delete operation.
        If e.AffectedRows = 1 Then
      
          MessageLabel.Text = e.AffectedRows.ToString() _
            & " record deleted successfully."
      
        Else
              
          MessageLabel.Text = e.AffectedRows.ToString() _
            & " records deleted successfully."
      
        End If
    
      Else
    
        ' Insert the code to handle the exception.
        MessageLabel.Text = e.Exception.Message
      
        ' Use the ExceptionHandled property to indicate that the 
        ' exception is already handled.
        e.ExceptionHandled = True
    
      End If
    
    End Sub
  
  </script>
    
  <head runat="server">
    <title>DetailsViewDeletedEventHandler Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>DetailsViewDeletedEventHandler Example</h3>
        
        <asp:detailsview id="CustomerDetailsView"
          datasourceid="DetailsViewSource"
          autogeneraterows="true"
          autogeneratedeletebutton="true"
          allowpaging="true"
          datakeynames="CustomerID" 
          runat="server">
        
          <pagersettings mode="NextPrevious"/>
        
        </asp:detailsview>
          
        <br/><br/>
        
        <asp:label id="MessageLabel"
          forecolor="Red"
          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="DetailsViewSource"
          selectcommand="Select [CustomerID], [CompanyName], [Address], 
            [City], [PostalCode], [Country] From [Customers]"
          deletecommand="Delete [Customers] 
            Where [CustomerID]=@CustomerID"
          connectionstring=
            "<%$ ConnectionStrings:NorthWindConnectionString%>" 
          runat="server"/>
            
      </form>
  </body>
</html>

Комментарии

Элемент DetailsView управления вызывает ItemDeleted событие при нажатии кнопки Удалить (кнопка со свойством CommandName "Удалить") в элементе управления, но после DetailsView того, как элемент управления удаляет запись. Это позволяет предоставить обработчик событий, который выполняет пользовательскую подпрограмму, например проверку результатов операции удаления при каждом возникновении этого события.

При создании делегата DetailsViewDeletedEventHandler необходимо указать метод, обрабатывающий событие. Чтобы связать событие с обработчиком событий, нужно добавить в событие экземпляр делегата. Обработчик событий вызывается всякий раз, когда происходит событие, если делегат не удален. Дополнительные сведения о делегатах обработчика событий см. в разделе Обработка и вызов событий.

Методы расширения

GetMethodInfo(Delegate)

Получает объект, представляющий метод, представленный указанным делегатом.

Применяется к

См. также раздел