SqlDataSource.Update Metodo

Definizione

Esegue un'operazione di aggiornamento utilizzando la stringa SQL UpdateCommand e tutti i parametri nell'insieme UpdateParameters.Performs an update operation using the UpdateCommand SQL string and any parameters that are in the UpdateParameters collection.

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

Restituisce

Valore che rappresenta il numero di righe aggiornate nel database sottostante.A value that represents the number of rows updated in the underlying database.

Eccezioni

L'oggetto SqlDataSource non può stabilire una connessione con l'origine dati sottostante.The SqlDataSource cannot establish a connection with the underlying data source.

Esempio

In questa sezione sono riportati due esempi di codice.This section contains two code examples. Nel primo esempio di codice viene illustrato come utilizzare un controllo SqlDataSource per visualizzare i dati in un controllo DropDownList e aggiornare i dati quando si fa clic sul pulsante Invia .The first code example demonstrates how to use a SqlDataSource control to display data in a DropDownList control and update data when the Submit button is clicked. Nel secondo esempio di codice viene illustrato come visualizzare i dati recuperati da un database di Microsoft SQL Server in un controllo DropDownList e aggiornare il record utilizzando un controllo TextBox.The second code example demonstrates how to display data that is retrieved from a Microsoft SQL Server database in a DropDownList control and update the record using a TextBox control.

Nell'esempio di codice riportato di seguito viene illustrato come utilizzare un controllo SqlDataSource per visualizzare i dati in un controllo DropDownList e aggiornare i dati quando si fa clic sul pulsante Invia .The following code example demonstrates how to use a SqlDataSource control to display data in a DropDownList control and update data when the Submit button is clicked. La proprietà UpdateCommand viene impostata con un'istruzione SQL con parametri e vengono aggiunti due parametri ControlParameter alla raccolta UpdateParameters.The UpdateCommand property is set with a parameterized SQL statement, and two ControlParameter parameters are added to the UpdateParameters collection. Quando si fa clic sul pulsante Submit , viene gestito l'evento OnClick per chiamare il metodo Update in modo esplicito.When the Submit button is clicked, the OnClick event is handled to call the Update method explicitly.

<%@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 On_Click(Object source, EventArgs e) {
    try {
        SqlDataSource1.Update();
    }
    catch (Exception except) {
        // Handle the Exception.
    }

    Label2.Text="The record was updated successfully!";
 }
</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 EmployeeID, LastName, Address FROM Employees"
          UpdateCommand="UPDATE Employees SET Address=@Address WHERE EmployeeID=@EmployeeID">
          <UpdateParameters>
              <asp:ControlParameter Name="Address" ControlId="TextBox1" PropertyName="Text"/>
              <asp:ControlParameter Name="EmployeeID" ControlId="DropDownList1" PropertyName="SelectedValue"/>
          </UpdateParameters>
      </asp:SqlDataSource>

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

      <br />
      <asp:Label id="Label1" runat="server" Text="Enter a new address for the selected user."
        AssociatedControlID="TextBox1" />
      <asp:TextBox id="TextBox1" runat="server" />
      <asp:Button id="Submit" runat="server" Text="Submit" OnClick="On_Click" />

      <br /><asp:Label id="Label2" runat="server" Text="" />

    </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_Click(ByVal source As Object, ByVal e As EventArgs)
    Try
        SqlDataSource1.Update()
    Catch except As Exception
        ' Handle the Exception.
    End Try

    Label2.Text="The record was updated successfully!"

 End Sub 'On_Click
</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 EmployeeID, LastName, Address FROM Employees"
          UpdateCommand="UPDATE Employees SET Address=@Address WHERE EmployeeID=@EmployeeID">
          <UpdateParameters>
              <asp:ControlParameter Name="Address" ControlId="TextBox1" PropertyName="Text"/>
              <asp:ControlParameter Name="EmployeeID" ControlId="DropDownList1" PropertyName="SelectedValue"/>
          </UpdateParameters>
      </asp:SqlDataSource>

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

      <br />
      <asp:Label id="Label1" runat="server" Text="Enter a new address for the selected user."
        AssociatedControlID="TextBox1" />
      <asp:TextBox id="TextBox1" runat="server" />
      <asp:Button id="Submit" runat="server" Text="Submit" OnClick="On_Click" />

      <br /><asp:Label id="Label2" runat="server" Text="" />
    </form>
  </body>
</html>

Nell'esempio di codice riportato di seguito viene illustrato come visualizzare i dati recuperati da un database di SQL Server in un controllo DropDownList e aggiornare il record utilizzando un controllo TextBox.The following code example demonstrates how to display data that is retrieved from a SQL Server database in a DropDownList control and update the record using a TextBox control. Nell'esempio viene illustrato come è possibile utilizzare un oggetto DbTransaction per aggiungere il contesto di transazione quando si utilizza il controllo SqlDataSource per aggiornare i dati.The example shows how you can use a DbTransaction object to add transaction context when using the SqlDataSource control to update data.

<%@Page  Language="C#" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<%@Import Namespace="System.Data.SqlClient" %>
<%@Import Namespace="System.Diagnostics" %>
<!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 On_Click(Object source, EventArgs e) {    
    SqlDataSource1.Update();
 }

 private void OnSqlUpdating(Object source, SqlDataSourceCommandEventArgs e) {
    DbCommand command = e.Command;
    DbConnection cx  = command.Connection;    
    cx.Open();    
    DbTransaction tx = cx.BeginTransaction();
    command.Transaction = tx;
 }

 private void OnSqlUpdated(Object source, SqlDataSourceStatusEventArgs e) {
    DbCommand command = e.Command;
    DbTransaction tx = command.Transaction;
    
    // In this code example the OtherProcessSucceeded variable represents
    // the outcome of some other process that occurs whenever the data is 
    // updated, and must succeed for the data change to be committed. For 
    // simplicity, we set this value to true. 
    bool OtherProcessSucceeded = true;
    
    if (OtherProcessSucceeded) {
        tx.Commit();
        Label2.Text="The record was updated successfully!";
    }
    else {
        tx.Rollback();
        Label2.Text="The record was not updated.";
    }
 }

</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 EmployeeID, LastName, Address FROM Employees"
          UpdateCommand="UPDATE Employees SET Address=@Address WHERE EmployeeID=@EmployeeID"
          OnUpdating="OnSqlUpdating"
          OnUpdated ="OnSqlUpdated">
          <UpdateParameters>
              <asp:ControlParameter Name="Address" ControlId="TextBox1" PropertyName="Text"/>
              <asp:ControlParameter Name="EmployeeID" ControlId="DropDownList1" PropertyName="SelectedValue"/>
          </UpdateParameters>
      </asp:SqlDataSource>

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

      <br />
      <asp:Label id="Label1" runat="server" Text="Enter a new address for the selected user."
        AssociatedControlID="TextBox1" />
      <asp:TextBox id="TextBox1" runat="server" />
      <asp:Button id="Submit" runat="server" Text="Submit" OnClick="On_Click" />

      <br /><asp:Label id="Label2" runat="server" Text="" />

    </form>
  </body>
</html>
<%@Page  Language="VB" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<%@Import Namespace="System.Diagnostics" %>
<!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_Click(ByVal source As Object, ByVal e As EventArgs)
        SqlDataSource1.Update()
 End Sub 'On_Click

 Sub On_Sql_Updating(ByVal source As Object, ByVal e As SqlDataSourceCommandEventArgs)
     Dim command as DbCommand
     Dim connection as DbConnection
     Dim transaction as DbTransaction
     
     command    = e.Command
     connection = command.Connection     
     connection.Open()     
     transaction = connection.BeginTransaction()
     command.Transaction = transaction
 
 End Sub 'On_Sql_Updating
 
 Sub On_Sql_Updated(ByVal source As Object, ByVal e As SqlDataSourceStatusEventArgs)
 
    Dim command As DbCommand
    Dim transaction As DbTransaction
    
    command = e.Command
    transaction = command.Transaction
    
    ' In this code example the OtherProcessSucceeded variable represents
    ' the outcome of some other process that occurs whenever the data is 
    ' updated, and must succeed for the data change to be committed. For 
    ' simplicity, we set this value to true. 
    Dim OtherProcessSucceeded as Boolean = True
    
    If (OtherProcessSucceeded) Then
        transaction.Commit()
        Label2.Text="The record was updated successfully!"
    Else    
        transaction.Rollback()
        Label2.Text="The record was not updated."
    End If
 End Sub ' On_Sql_Updated
</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 EmployeeID, LastName, Address FROM Employees"
          UpdateCommand="UPDATE Employees SET Address=@Address WHERE EmployeeID=@EmployeeID"
          OnUpdating="On_Sql_Updating"
          OnUpdated ="On_Sql_Updated">
          <UpdateParameters>
              <asp:ControlParameter Name="Address" ControlId="TextBox1" PropertyName="Text"/>
              <asp:ControlParameter Name="EmployeeID" ControlId="DropDownList1" PropertyName="SelectedValue"/>
          </UpdateParameters>
      </asp:SqlDataSource>

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

      <br />
      <asp:Label id="Label1" runat="server" Text="Enter a new address for the selected user."
        AssociatedControlID="TextBox1" />
      <asp:TextBox id="TextBox1" runat="server" />
      <asp:Button id="Submit" runat="server" Text="Submit" OnClick="On_Click" />

      <br /><asp:Label id="Label2" runat="server" Text="" />

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

Commenti

Il metodo Update viene chiamato automaticamente dai controlli GridView, DetailsViewe FormView durante il postback se i dati sono stati modificati.The Update method is automatically called by the GridView, DetailsView, and FormView controls during postback if the data has been changed. Per i dati che sono stati modificati in altri controlli, il metodo Update può essere chiamato in modo esplicito durante il postback durante l'evento di Load.For data that has been changed in other controls, the Update method can be explicitly called on postback during the Load event.

Prima di eseguire l'operazione di Update, viene chiamato il metodo OnUpdating per generare l'evento di Updating.Before the Update operation is performed, the OnUpdating method is called to raise the Updating event. È possibile gestire questo evento per esaminare i valori dei parametri e per eseguire qualsiasi pre-elaborazione prima di un'operazione di Update.You can handle this event to examine the values of the parameters and to perform any preprocessing before an Update operation.

Al termine dell'operazione di Update, viene chiamato il metodo OnUpdated per generare l'evento di Updated.After the Update operation completes, the OnUpdated method is called to raise the Updated event. È possibile gestire questo evento per esaminare i valori restituiti e i codici di errore e per eseguire qualsiasi post-elaborazione.You can handle this event to examine any return values and error codes and to perform any post-processing.

Il metodo Update delega al metodo Update dell'oggetto SqlDataSourceView associato al controllo SqlDataSource.The Update method delegates to the Update method of the SqlDataSourceView object that is associated with the SqlDataSource control. Per eseguire un'operazione di aggiornamento, il SqlDataSourceView compila un oggetto DbCommand utilizzando il testo UpdateCommand ed eventuali proprietà UpdateParameters associate, quindi esegue l'oggetto DbCommand sul database sottostante.To perform an update operation, the SqlDataSourceView builds a DbCommand object using the UpdateCommand text and any associated UpdateParameters properties, and then executes the DbCommand object against the underlying database.

Importante

I valori vengono inseriti nei parametri senza convalida, che rappresenta una potenziale minaccia per la sicurezza.Values are inserted into parameters without validation, which is a potential security threat. Utilizzare l'evento Updating per convalidare i valori dei parametri prima di eseguire la query.Use the Updating event to validate parameter values before executing the query. Per altre informazioni, vedere Cenni preliminari sugli attacchi tramite script.For more information, see Script Exploits Overview.

Si applica a

Vedi anche