ListView.ItemInserted Evento

Definizione

Si verifica quando è richiesta un'operazione di inserimento, dopo che il controllo ListView ha inserito l'elemento nell'origine dati.

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) 

Tipo evento

Esempio

Nell'esempio seguente viene illustrato come aggiungere un gestore eventi per l'evento ItemInserted .

Importante

L'esempio include una casella di testo che accetta l'input dell'utente e rappresenta quindi una potenziale minaccia alla sicurezza. Per impostazione predefinita, le pagine Web ASP.NET verificano che l'input dell'utente non includa script o elementi HTML. Per altre informazioni, vedere Cenni preliminari sugli attacchi tramite script.

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

Commenti

Il ListView controllo genera l'evento ItemInserted quando viene fatto clic su un pulsante Insert nel InsertItemTemplate modello oppure viene chiamato il InsertNewItem metodo, dopo che il controllo inserisce l'elemento ListView nell'origine dati. Un pulsante Insert è un controllo pulsante la cui CommandName proprietà è impostata su "Inserisci". Ciò consente di eseguire una routine personalizzata ogni volta che si verifica questo evento, ad esempio controllare i risultati di un'operazione di inserimento.

Un ListViewInsertedEventArgs oggetto viene passato al gestore eventi, che consente di determinare il numero di record interessati. Consente inoltre di determinare quali eccezioni potrebbero verificarsi. Per determinare il numero di record interessati dall'operazione di inserimento, usare la AffectedRows proprietà . Per determinare se si sono verificate eccezioni, usare la Exception proprietà . È anche possibile indicare se l'eccezione è stata gestita nel gestore eventi impostando la ExceptionHandled proprietà. Se si desidera accedere ai valori del record inserito, usare la Values proprietà .

Se la AffectedRows proprietà segnala che non sono stati inseriti elementi, è possibile ribinare i valori di inserimento nel InsertItemTemplate modello impostando la KeepInInsertMode proprietà su true.

Per altre informazioni su come gestire gli eventi, vedere la gestione e generazione di eventi.

Si applica a

Vedi anche