ListView.ItemInserted Событие

Определение

Происходит при запросе операции вставки, после того как элемент управления ListView вставил элемент в источник данных.

public:
 event EventHandler<System::Web::UI::WebControls::ListViewInsertedEventArgs ^> ^ ItemInserted;
public event EventHandler<System.Web.UI.WebControls.ListViewInsertedEventArgs> ItemInserted;
member this.ItemInserted : EventHandler<System.Web.UI.WebControls.ListViewInsertedEventArgs> 
Public Custom Event ItemInserted As EventHandler(Of ListViewInsertedEventArgs) 

Тип события

Примеры

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

Важно!

В этом примере имеется текстовое поле, принимающее вводимые пользователем данные, что является потенциальной угрозой безопасности. По умолчанию данные, вводимые пользователем на веб-страницах ASP.NET, проверяются на наличие скриптов и HTML-элементов. Дополнительные сведения см. в разделе Общие сведения об использовании сценариев.

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

  //<Snippet3>
  void ContactsListView_ItemInserted(Object sender, ListViewInsertedEventArgs e)
  {
    if (e.Exception != null)
    {
      if (e.AffectedRows == 0)
      {
        e.KeepInInsertMode = true;
        Message.Text = "An exception occurred inserting the new Contact. " +
          "Please verify your values and try again.";
      }
      else
        Message.Text = "An exception occurred inserting the new Contact. " +
          "Please verify the values in the newly inserted item.";

      e.ExceptionHandled = true;
    }
  }
  //</Snippet3>

  protected void Page_Load(object sender, EventArgs e)
  {
    Message.Text = "";
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head id="Head1" runat="server">
    <title>ListView.ItemInserted Example</title>
  </head>
  <body>
    <form id="form1" runat="server">
        
      <h3>ListViewItemInserted Example</h3>
            
      <asp:Label ID="Message"
        ForeColor="Red"          
        runat="server"/>
      <br/>
      
      <asp:ListView ID="ContactsListView" 
        DataSourceID="ContactsDataSource" 
        DataKeyNames="ContactID"
        OnItemInserted="ContactsListView_ItemInserted"  
        InsertItemPosition="LastItem"
        runat="server">
        <LayoutTemplate>
          <table cellpadding="2" border="1" runat="server" id="tblContacts" width="640px">
            <tr runat="server" id="itemPlaceholder" />
          </table>
          <asp:DataPager runat="server" ID="PeopleDataPager" PageSize="12">
            <Fields>
              <asp:NextPreviousPagerField 
                ShowFirstPageButton="true" ShowLastPageButton="true"
                FirstPageText="|&lt;&lt; " LastPageText=" &gt;&gt;|"
                NextPageText=" &gt; " PreviousPageText=" &lt; " />
            </Fields>
          </asp:DataPager>
        </LayoutTemplate>
        <ItemTemplate>
          <tr runat="server">
            <td valign="top">
              <asp:Label ID="FirstNameLabel" runat="server" Text='<%#Eval("FirstName") %>' />
              <asp:Label ID="LastNameLabel" runat="server" Text='<%#Eval("LastName") %>' />
            </td>
            <td>&nbsp;
              <asp:Label ID="EmailLabel" runat="server" Text='<%#Eval("EmailAddress") %>' />
            </td>
          </tr>
        </ItemTemplate>
        <InsertItemTemplate>
          <tr style="background-color:#D3D3D3">
            <td valign="top">
              <asp:Label runat="server" ID="FirstNameLabel" 
                AssociatedControlID="FirstNameTextBox" Text="First Name"/>
              <asp:TextBox ID="FirstNameTextBox" runat="server" 
                Text='<%#Bind("FirstName") %>' /><br />
              <asp:Label runat="server" ID="LastNameLabel" 
                AssociatedControlID="LastNameTextBox" Text="Last Name" />
              <asp:TextBox ID="LastNameTextBox" runat="server" 
                Text='<%#Bind("LastName") %>' /><br />
              <asp:Label runat="server" ID="EmailLabel" 
                AssociatedControlID="EmailTextBox" Text="Email" />
              <asp:TextBox ID="EmailTextBox" runat="server" 
                Text='<%#Bind("EmailAddress") %>' />
            </td>
            <td>
              <asp:LinkButton ID="InsertButton" runat="server" 
                CommandName="Insert" Text="Insert" />
            </td>
          </tr>
        </InsertItemTemplate>
      </asp:ListView>

      <!-- This example uses Microsoft SQL Server and connects      -->
      <!-- to the AdventureWorks sample database. Use an ASP.NET    -->
      <!-- expression to retrieve the connection string value       -->
      <!-- from the Web.config file.                                -->
      <asp:SqlDataSource ID="ContactsDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
        SelectCommand="SELECT [ContactID], [FirstName], [LastName], [EmailAddress] 
          FROM Person.Contact"
        InsertCommand="INSERT INTO Person.Contact
          ([FirstName], [LastName], [EmailAddress], [PasswordHash], [PasswordSalt]) 
          Values(@FirstName, @LastName, @EmailAddress, '', '');
          SELECT @ContactID = SCOPE_IDENTITY()">
        <InsertParameters>
          <asp:Parameter Name="FirstName" />
          <asp:Parameter Name="LastName" />
          <asp:Parameter Name="EmailAddress" />
          <asp:Parameter Name="ContactID" Type="Int32" Direction="Output" />
        </InsertParameters>
      </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">

  '<Snippet3>
  Sub ContactsListView_ItemInserted(ByVal sender As Object, ByVal e As ListViewInsertedEventArgs)

    If e.Exception IsNot Nothing Then

      If e.AffectedRows = 0 Then
        e.KeepInInsertMode = True
        Message.Text = "An exception occurred inserting the new Contact. " & _
          "Please verify your values and try again."
      Else
        Message.Text = "An exception occurred inserting the new Contact. " & _
          "Please verify the values in the newly inserted item."
      End If

      e.ExceptionHandled = True
    End If
  End Sub
  '</Snippet3>

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Message.Text = ""
  End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head id="Head1" runat="server">
    <title>ListView.ItemInserted Example</title>
  </head>
  <body>
    <form id="form1" runat="server">
        
      <h3>ListViewItemInserted Example</h3>
            
      <asp:Label ID="Message"
        ForeColor="Red"          
        runat="server"/>
      <br/>
      
      <asp:ListView ID="ContactsListView" 
        DataSourceID="ContactsDataSource" 
        DataKeyNames="ContactID"
        OnItemInserted="ContactsListView_ItemInserted"  
        InsertItemPosition="LastItem"
        runat="server">
        <LayoutTemplate>
          <table cellpadding="2" border="1" runat="server" id="tblContacts" width="640px">
            <tr runat="server" id="itemPlaceholder" />
          </table>
          <asp:DataPager runat="server" ID="PeopleDataPager" PageSize="12">
            <Fields>
              <asp:NextPreviousPagerField 
                ShowFirstPageButton="true" ShowLastPageButton="true"
                FirstPageText="|&lt;&lt; " LastPageText=" &gt;&gt;|"
                NextPageText=" &gt; " PreviousPageText=" &lt; " />
            </Fields>
          </asp:DataPager>
        </LayoutTemplate>
        <ItemTemplate>
          <tr runat="server">
            <td valign="top">
              <asp:Label ID="FirstNameLabel" runat="server" Text='<%#Eval("FirstName") %>' />
              <asp:Label ID="LastNameLabel" runat="server" Text='<%#Eval("LastName") %>' />
            </td>
            <td>&nbsp;
              <asp:Label ID="EmailLabel" runat="server" Text='<%#Eval("EmailAddress") %>' />
            </td>
          </tr>
        </ItemTemplate>
        <InsertItemTemplate>
          <tr style="background-color:#D3D3D3">
            <td valign="top">
              <asp:Label runat="server" ID="FirstNameLabel" 
                AssociatedControlID="FirstNameTextBox" Text="First Name"/>
              <asp:TextBox ID="FirstNameTextBox" runat="server" 
                Text='<%#Bind("FirstName") %>' /><br />
              <asp:Label runat="server" ID="LastNameLabel" 
                AssociatedControlID="LastNameTextBox" Text="Last Name" />
              <asp:TextBox ID="LastNameTextBox" runat="server" 
                Text='<%#Bind("LastName") %>' /><br />
              <asp:Label runat="server" ID="EmailLabel" 
                AssociatedControlID="EmailTextBox" Text="Email" />
              <asp:TextBox ID="EmailTextBox" runat="server" 
                Text='<%#Bind("EmailAddress") %>' />
            </td>
            <td>
              <asp:LinkButton ID="InsertButton" runat="server" 
                CommandName="Insert" Text="Insert" />
            </td>
          </tr>
        </InsertItemTemplate>
      </asp:ListView>

      <!-- This example uses Microsoft SQL Server and connects      -->
      <!-- to the AdventureWorks sample database. Use an ASP.NET    -->
      <!-- expression to retrieve the connection string value       -->
      <!-- from the Web.config file.                                -->
      <asp:SqlDataSource ID="ContactsDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
        SelectCommand="SELECT [ContactID], [FirstName], [LastName], [EmailAddress] 
          FROM Person.Contact"
        InsertCommand="INSERT INTO Person.Contact
          ([FirstName], [LastName], [EmailAddress], [PasswordHash], [PasswordSalt]) 
          Values(@FirstName, @LastName, @EmailAddress, '', '');
          SELECT @ContactID = SCOPE_IDENTITY()">
        <InsertParameters>
          <asp:Parameter Name="FirstName" />
          <asp:Parameter Name="LastName" />
          <asp:Parameter Name="EmailAddress" />
          <asp:Parameter Name="ContactID" Type="Int32" Direction="Output" />
        </InsertParameters>
      </asp:SqlDataSource>
      
    </form>
  </body>
</html>

Комментарии

Элемент ListView управления вызывает ItemInserted событие при нажатии кнопки Вставка в InsertItemTemplate шаблоне или InsertNewItem вызове метода после ListView того, как элемент управления вставляет элемент в источник данных. (Кнопка Вставка — это элемент управления кнопкой, свойство которого CommandName имеет значение "Вставка".) Это позволяет выполнять пользовательскую подпрограмму при каждом возникновении этого события, например проверять результаты операции вставки.

Объект ListViewInsertedEventArgs передается обработчику событий, что позволяет определить количество затронутых записей. Он также позволяет определить, какие исключения могли возникнуть. Чтобы определить количество записей, затронутых операцией вставки, используйте AffectedRows свойство . Чтобы определить, возникли ли исключения, используйте Exception свойство . Можно также указать, было ли обработано исключение в обработчике событий, задав ExceptionHandled свойство . Если вы хотите получить доступ к значениям вставленной записи, используйте Values свойство .

AffectedRows Если свойство сообщает, что элементы не были вставлены, можно повторно привязать значения вставки к шаблонуInsertItemTemplate, задав для KeepInInsertMode свойства значение true.

Дополнительные сведения об обработке событий см. в разделе Обработка и создание событий.

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

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