共用方式為


使用 SqlDataSource 控制項修改資料

更新:2007 年 11 月

您可以使用 SqlDataSource 控制項修改資料庫中的資料。在更新案例中最常使用 SqlDataSource 控制項來擷取資料,然後使用資料繫結 Web 伺服器控制項,例如 GridViewDetailsViewFormView 控制項來顯示資料。您可以設定資料繫結控制項和 SqlDataSource 來更新資料。大部分資料繫結控制項可以讓您設定為支援 Insert、Update 和 Delete 作業,並且它們會將要更新的值傳遞至資料來源控制項。然後資料來源控制項會使用 SQL 陳述式或預存程序,將更新的值送出至資料庫。

SqlDataSource 控制項是用來一次更新一筆記錄的資料。如果您需要執行批次更新,就必須在 ASP.NET 應用程式中寫入明確的重複循環邏輯。

基本概念

若要使用 SqlDataSource 控制項修改資料庫中的資料,您至少需要設定下列屬性:

  • ProviderName 設定為代表正在使用之資料庫的 ADO.NET 提供者名稱。

  • ConnectionString 設定為資料庫使用的連接字串。

  • SqlDataSource 命令屬性 設定為修改資料庫中資料的 SQL 陳述式。

下列小節詳細描述了這些屬性。

提供者名稱

ProviderName 屬性設定為儲存資料之資料庫類型的 ADO.NET 提供者名稱,其中包含下列所示:

  • 如果使用的是 Microsoft SQL Server,請將 ProviderName 屬性設定為 "System.Data.SqlClient"。如果您不指定的話,這是預設提供者。

  • 如果使用的是 Oracle 資料庫,請將 ProviderName 屬性設定為 "System.Data.OracleClient"。

  • 如果使用的是 OLE DB 資料來源,請將 ProviderName 屬性設定為 "System.Data.OleDb"。

  • 如果使用的是 ODBC 資料來源,請將 ProviderName 屬性設定為 "System.Data.Odbc"。

連接字串

設定 ConnectionString 屬性以連接至特定資料庫。建議您將連接字串儲存在應用程式組態檔的 ConnectionStrings 項目中。然後您可以在控制項標記中使用 <%$ ConnectionStrings:connectionStringName %> 語法參考儲存的連接字串。連接字串必須是指定 ProviderName 的有效連接字串。

Commands

SqlDataSource 控制項有三個可以包含修改資料之 SQL 陳述式的命令屬性:InsertCommandUpdateCommandDeleteCommand 屬性。命令屬性可以設定為 SQL 陳述式,或是設定為預存程序名稱 (如果資料來源支援預存程序的話)。SQL 陳述式的實際語法是依照資料的結構描述和您所使用的資料庫而定。如果資料來源支援的話,陳述式可以包含參數。

注意事項:

設定命令屬性的陳述式,與撰寫 ADO.NET 資料管理程式碼時,設定 ADO.NET IDbCommand 物件之 CommandText 屬性的陳述式相同。

每次呼叫 Update 方法時都會執行 UpdateCommand 屬性中的 SQL 陳述式。當使用者按一下 GridViewFormViewDetailsView 控制項中的 [更新] 按鈕時,資料繫結控制項就會隱含地呼叫 Update 方法。您也可以從自己的程式碼中明確呼叫這個方法。SqlDataSource 控制項的 InsertDelete 方法工作方式類似。

下列程式碼範例會示範如何使用 SqlDataSource 控制項,透過使用 FormView 控制項插入、更新和刪除資料錄。這個範例連接至 SQL Server Northwind 資料庫。

<%@ Page language="VB" %>

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

  Sub EmployeesGridView_OnSelectedIndexChanged(sender As Object, e As EventArgs)
    EmployeeDetailsSqlDataSource.SelectParameters("EmpID").DefaultValue = _
      EmployeesGridView.SelectedValue.ToString()
    EmployeeFormView.DataBind()
  End Sub

  Sub EmployeeFormView_ItemUpdated(sender As Object, e As FormViewUpdatedEventArgs)
    EmployeesGridView.DataBind()
  End Sub

  Sub EmployeeFormView_ItemDeleted(sender As Object, e As FormViewDeletedEventArgs)
    EmployeesGridView.DataBind()
  End Sub

  Sub EmployeeDetailsSqlDataSource_OnInserted(sender As Object, e As SqlDataSourceStatusEventArgs)
    Dim command As System.Data.Common.DbCommand = e.Command    

    EmployeeDetailsSqlDataSource.SelectParameters("EmpID").DefaultValue = _
      command.Parameters("@EmpID").Value.ToString()

    EmployeesGridView.DataBind()
    EmployeeFormView.DataBind()
  End Sub

</script>

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

      <h3>FormView Example</h3>

        <table cellspacing="10">

          <tr>
            <td>
              <asp:GridView ID="EmployeesGridView" 
                DataSourceID="EmployeesSqlDataSource" 
                AutoGenerateColumns="false"
                DataKeyNames="EmployeeID" 
                OnSelectedIndexChanged="EmployeesGridView_OnSelectedIndexChanged"
                RunAt="Server">

                <HeaderStyle backcolor="Navy"
                  forecolor="White" />

                <Columns>

                  <asp:ButtonField Text="Details..."
                    HeaderText="Show<BR>Details"
                    CommandName="Select"/>  

                  <asp:BoundField DataField="EmployeeID" HeaderText="Employee ID"/>
                  <asp:BoundField DataField="LastName"   HeaderText="Last Name"/>                        
                  <asp:BoundField DataField="FirstName"  HeaderText="First Name"/>

                </Columns>

              </asp:GridView>

            </td>

            <td valign="top">

              <asp:FormView ID="EmployeeFormView"
                DataSourceID="EmployeeDetailsSqlDataSource"
                DataKeyNames="EmployeeID"     
                Gridlines="Both" 
                OnItemUpdated="EmployeeFormView_ItemUpdated"
                OnItemDeleted="EmployeeFormView_ItemDeleted"      
                RunAt="server">

                <HeaderStyle backcolor="Navy"
                  forecolor="White"/>

                <RowStyle backcolor="White"/>         

                <EditRowStyle backcolor="LightCyan"/>

                <ItemTemplate>
                  <table>
                    <tr><td align="right"><b>Employee ID:</b></td><td><%# Eval("EmployeeID") %></td></tr>
                    <tr><td align="right"><b>First Name:</b></td> <td><%# Eval("FirstName") %></td></tr>
                    <tr><td align="right"><b>Last Name:</b></td>  <td><%# Eval("LastName") %></td></tr>
                    <tr>
                      <td colspan="2">
                        <asp:LinkButton ID="EditButton"
                                        Text="Edit"
                                        CommandName="Edit"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="NewButton"
                                        Text="New"
                                        CommandName="New"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="DeleteButton"
                                        Text="Delete"
                                        CommandName="Delete"
                                        RunAt="server"/>
                      </td>
                    </tr>
                  </table>                 
                </ItemTemplate>

                <EditItemTemplate>


                  <table>
                    <tr><td align="right"><b>Employee ID:</b></td><td><%# Eval("EmployeeID") %></td></tr>
                    <tr><td align="right"><b>First Name:</b></td>
                        <td><asp:TextBox ID="EditFirstNameTextBox" 
                                         Text='<%# Bind("FirstName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr><td align="right"><b>Last Name:</b></td>
                        <td><asp:TextBox ID="EditLastNameTextBox" 
                                         Text='<%# Bind("LastName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr>
                      <td colspan="2">
                        <asp:LinkButton ID="UpdateButton"
                                        Text="Update"
                                        CommandName="Update"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="CancelUpdateButton"
                                        Text="Cancel"
                                        CommandName="Cancel"
                                        RunAt="server"/>
                      </td>
                    </tr>
                  </table>                 
                </EditItemTemplate>

                <InsertItemTemplate>


                  <table>
                    <tr><td align="right"><b>First Name:</b></td>
                        <td><asp:TextBox ID="InsertFirstNameTextBox" 
                                         Text='<%# Bind("FirstName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr><td align="right"><b>Last Name:</b></td>
                        <td><asp:TextBox ID="InsertLastNameTextBox" 
                                         Text='<%# Bind("LastName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr>
                      <td colspan="2">
                        <asp:LinkButton ID="InsertButton"
                                        Text="Insert"
                                        CommandName="Insert"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="CancelInsertButton"
                                        Text="Cancel"
                                        CommandName="Cancel"
                                        RunAt="server"/>
                      </td>
                    </tr>
                  </table>                 
                </InsertItemTemplate>

              </asp:FormView>

            </td>

          </tr>

        </table>

        <asp:sqlDataSource ID="EmployeesSqlDataSource"  
          selectCommand="SELECT EmployeeID, FirstName, LastName FROM Employees" 
          connectionstring="<%$ ConnectionStrings:NorthwindConnection %>" 
          RunAt="server">
        </asp:sqlDataSource>

        <asp:sqlDataSource ID="EmployeeDetailsSqlDataSource" 
          SelectCommand="SELECT EmployeeID, LastName, FirstName FROM Employees WHERE EmployeeID = @EmpID"

          InsertCommand="INSERT INTO Employees(LastName, FirstName) VALUES (@LastName, @FirstName); 
                         SELECT @EmpID = SCOPE_IDENTITY()"
          UpdateCommand="UPDATE Employees SET LastName=@LastName, FirstName=@FirstName 
                           WHERE EmployeeID=@EmployeeID"
          DeleteCommand="DELETE Employees WHERE EmployeeID=@EmployeeID"

          ConnectionString="<%$ ConnectionStrings:NorthwindConnection %>"
          OnInserted="EmployeeDetailsSqlDataSource_OnInserted"
          RunAt="server">

          <SelectParameters>
            <asp:Parameter Name="EmpID" Type="Int32" DefaultValue="0" />
          </SelectParameters>

          <InsertParameters>
            <asp:Parameter Name="EmpID" Direction="Output" Type="Int32" DefaultValue="0" />
          </InsertParameters>

        </asp:sqlDataSource>

      </form>
  </body>
</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 >

  void EmployeesGridView_OnSelectedIndexChanged(Object sender, EventArgs e)
  {
    EmployeeDetailsSqlDataSource.SelectParameters["EmpID"].DefaultValue = 
      EmployeesGridView.SelectedValue.ToString();
    EmployeeFormView.DataBind();
  }

  void EmployeeFormView_ItemUpdated(Object sender, FormViewUpdatedEventArgs e)
  {
    EmployeesGridView.DataBind();
  }

  void EmployeeFormView_ItemDeleted(Object sender, FormViewDeletedEventArgs e)
  {
    EmployeesGridView.DataBind();
  }

  void EmployeeDetailsSqlDataSource_OnInserted(Object sender, SqlDataSourceStatusEventArgs e)
  {
    System.Data.Common.DbCommand command = e.Command;    

    EmployeeDetailsSqlDataSource.SelectParameters["EmpID"].DefaultValue = 
      command.Parameters["@EmpID"].Value.ToString();

    EmployeesGridView.DataBind();
    EmployeeFormView.DataBind();
  }

</script>

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

      <h3>FormView Example</h3>

        <table cellspacing="10">

          <tr>
            <td>
              <asp:GridView ID="EmployeesGridView" 
                DataSourceID="EmployeesSqlDataSource" 
                AutoGenerateColumns="false"
                DataKeyNames="EmployeeID" 
                OnSelectedIndexChanged="EmployeesGridView_OnSelectedIndexChanged"
                RunAt="Server">

                <HeaderStyle backcolor="Navy"
                  forecolor="White" />

                <Columns>

                  <asp:ButtonField Text="Details..."
                    HeaderText="Show<BR>Details"
                    CommandName="Select"/>  

                  <asp:BoundField DataField="EmployeeID" HeaderText="Employee ID"/>
                  <asp:BoundField DataField="LastName"   HeaderText="Last Name"/>                        
                  <asp:BoundField DataField="FirstName"  HeaderText="First Name"/>

                </Columns>

              </asp:GridView>

            </td>

            <td valign="top">

              <asp:FormView ID="EmployeeFormView"
                DataSourceID="EmployeeDetailsSqlDataSource"
                DataKeyNames="EmployeeID"     
                Gridlines="Both" 
                OnItemUpdated="EmployeeFormView_ItemUpdated"
                OnItemDeleted="EmployeeFormView_ItemDeleted"      
                RunAt="server">

                <HeaderStyle backcolor="Navy"
                  forecolor="White"/>

                <RowStyle backcolor="White"/>         

                <EditRowStyle backcolor="LightCyan"/>

                <ItemTemplate>
                  <table>
                    <tr><td align="right"><b>Employee ID:</b></td><td><%# Eval("EmployeeID") %></td></tr>
                    <tr><td align="right"><b>First Name:</b></td> <td><%# Eval("FirstName") %></td></tr>
                    <tr><td align="right"><b>Last Name:</b></td>  <td><%# Eval("LastName") %></td></tr>
                    <tr>
                      <td colspan="2">
                        <asp:LinkButton ID="EditButton"
                                        Text="Edit"
                                        CommandName="Edit"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="NewButton"
                                        Text="New"
                                        CommandName="New"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="DeleteButton"
                                        Text="Delete"
                                        CommandName="Delete"
                                        RunAt="server"/>
                      </td>
                    </tr>
                  </table>                 
                </ItemTemplate>

                <EditItemTemplate>


                  <table>
                    <tr><td align="right"><b>Employee ID:</b></td><td><%# Eval("EmployeeID") %></td></tr>
                    <tr><td align="right"><b>First Name:</b></td>
                        <td><asp:TextBox ID="EditFirstNameTextBox" 
                                         Text='<%# Bind("FirstName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr><td align="right"><b>Last Name:</b></td>
                        <td><asp:TextBox ID="EditLastNameTextBox" 
                                         Text='<%# Bind("LastName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr>
                      <td colspan="2">
                        <asp:LinkButton ID="UpdateButton"
                                        Text="Update"
                                        CommandName="Update"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="CancelUpdateButton"
                                        Text="Cancel"
                                        CommandName="Cancel"
                                        RunAt="server"/>
                      </td>
                    </tr>
                  </table>                 
                </EditItemTemplate>

                <InsertItemTemplate>


                  <table>
                    <tr><td align="right"><b>First Name:</b></td>
                        <td><asp:TextBox ID="InsertFirstNameTextBox" 
                                         Text='<%# Bind("FirstName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr><td align="right"><b>Last Name:</b></td>
                        <td><asp:TextBox ID="InsertLastNameTextBox" 
                                         Text='<%# Bind("LastName") %>' 
                                         RunAt="Server" /></td></tr>
                    <tr>
                      <td colspan="2">
                        <asp:LinkButton ID="InsertButton"
                                        Text="Insert"
                                        CommandName="Insert"
                                        RunAt="server"/>
                        &nbsp;
                        <asp:LinkButton ID="CancelInsertButton"
                                        Text="Cancel"
                                        CommandName="Cancel"
                                        RunAt="server"/>
                      </td>
                    </tr>
                  </table>                 
                </InsertItemTemplate>

              </asp:FormView>

            </td>

          </tr>

        </table>

        <asp:sqlDataSource ID="EmployeesSqlDataSource"  
          selectCommand="SELECT EmployeeID, FirstName, LastName FROM Employees" 
          connectionstring="<%$ ConnectionStrings:NorthwindConnection %>" 
          RunAt="server">
        </asp:sqlDataSource>

        <asp:sqlDataSource ID="EmployeeDetailsSqlDataSource" 
          SelectCommand="SELECT EmployeeID, LastName, FirstName FROM Employees WHERE EmployeeID = @EmpID"

          InsertCommand="INSERT INTO Employees(LastName, FirstName) VALUES (@LastName, @FirstName); 
                         SELECT @EmpID = SCOPE_IDENTITY()"
          UpdateCommand="UPDATE Employees SET LastName=@LastName, FirstName=@FirstName 
                           WHERE EmployeeID=@EmployeeID"
          DeleteCommand="DELETE Employees WHERE EmployeeID=@EmployeeID"

          ConnectionString="<%$ ConnectionStrings:NorthwindConnection %>"
          OnInserted="EmployeeDetailsSqlDataSource_OnInserted"
          RunAt="server">

          <SelectParameters>
            <asp:Parameter Name="EmpID" Type="Int32" DefaultValue="0" />
          </SelectParameters>

          <InsertParameters>
            <asp:Parameter Name="EmpID" Direction="Output" Type="Int32" DefaultValue="0" />
          </InsertParameters>

        </asp:sqlDataSource>

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

如果您使用的資料庫支援預存程序,命令可以是預存程序的名稱。如果您使用預存程序更新資料,就必須將 UpdateCommandType 屬性設定為 StoredProcedure

參數

參數是用來將 Insert、Update 和 Delete 作業的值傳送至資料來源。參數名稱和值是根據繫結至控制項的資料欄位,或是明確定義的參數物件。資料繫結控制項的參數,會同時包含資料作業和關鍵值的值以辨認特定資料列,如同繫結控制項的 DataKeyNames 屬性所定義。

您可以建立明確 Parameter 定義指定參數順序、類型和方向,以及並非根據繫結至控制項之欄位的其他參數。這項功能的範例之一是輸出參數,可以傳回資料來源 (例如自動遞增主索引鍵或是日期時間戳記) 所自動產生的值。

注意事項:

當使用不支援 SQL 陳述式中的具名參數,而是使用 '?' 替代符號指定參數的 System.Data.OleDbSystem.Data.Odbc 提供者時,明確指定參數就特別重要。在這些情況中,則應該依照關聯 SQL 陳述式中指定的順序定義參數。

如需使用參數的資訊和範例,請參閱使用參數和 SqlDataSource 控制項資料來源控制項如何建立資料繫結欄位的參數

事件

SqlDataSource 控制項會引發您能夠處理的事件,以便在控制項執行 Insert、Update 和 Delete 作業的前後執行自己的程式碼。

SqlDataSource 控制項在執行對應命令屬性的 SQL 陳述式之前,會引發 InsertingUpdatingDeleting 事件。您可以為這些事件加入處理常式,以便在執行陳述式之前管理、重新排列或驗證陳述式的參數,以及取消命令。例如,如果您搭配 SqlDataSource 控制項使用 QueryStringParameter,可以處理 Updating 事件以便在執行更新前驗證參數的值 (根據預設,QueryStringParameter 會取得查詢字串變數的值,然後在不經過驗證的情況下送出至資料庫)。如果值無法接受,您可以將事件的 SqlDataSourceCommandEventArgs 物件之 Cancel 屬性設定為 true 以取消更新。

在資料庫作業完成後,SqlDataSource 控制項會引發 InsertedUpdatedDeleted 事件。您可以處理這些事件以判斷在資料庫作業期間是否擲回例外狀況、了解有多少資料錄受到作業影響,或是檢視資料庫作業傳回的任何輸出值。

例如,下列程式碼範例會使用 UpdatingUpdated 事件在交易中執行 UpdateCommand

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

 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 >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >
      <asp:SqlDataSource
          id="SqlDataSource1"
          
          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"
          
          DataTextField="LastName"
          DataValueField="EmployeeID"
          DataSourceID="SqlDataSource1">
      </asp:DropDownList>

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

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

    </form>
  </body>
</html>
<%@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 >

 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 >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >
      <asp:SqlDataSource
          id="SqlDataSource1"
          
          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"
          
          DataTextField="LastName"
          DataValueField="EmployeeID"
          DataSourceID="SqlDataSource1">
      </asp:DropDownList>

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

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

    </form>
  </body>
</html>
<%@Page  Language="VJ#" %>
<%@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 >

     private void On_Click(Object source, System.EventArgs e)
    {
        try {
            SqlDataSource1.Update();
        }
        catch (System.Exception except) {
            // Handle Exception
        }

        Label2.set_Text("The record was updated successfully!");
    } //On_Click

    private void OnSqlUpdate(Object source, SqlDataSourceCommandEventArgs e)
    {
        // Log the command in the Event Log on the Web server.
        String logInfo = e.get_Command().get_CommandText() 
            + " is being submitted to the database.";

        IEnumerator ie = e.get_Command().get_Parameters().GetEnumerator();
        while (ie.MoveNext()) {
            DbParameter param = ((DbParameter)(ie.get_Current()));
            logInfo = logInfo + " " + param.get_ParameterName()+ "=" 
            + param.get_Value();
        }

        EventLog log = new EventLog();
        log.set_Log("Application");
        log.set_Source("ASP.NET Example");
        log.WriteEntry(logInfo);
    } //OnSqlUpdate    

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >
      <asp:SqlDataSource
          id="SqlDataSource1"
          
          ConnectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;"
          SelectCommand="SELECT EmployeeID, LastName, Address FROM Employees"
          UpdateCommand="UPDATE Employees SET Address=@Address WHERE EmployeeID=@EmployeeID"
          OnUpdating="OnSqlUpdate">
          <UpdateParameters>
              <asp:ControlParameter Name="Address" ControlId="TextBox1" PropertyName="Text"/>
              <asp:ControlParameter Name="EmployeeID" ControlId="DropDownList1" PropertyName="SelectedValue"/>
          </UpdateParameters>
      </asp:SqlDataSource>

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

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

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

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

衝突偵測

SqlDataSource 控制項可以使用開放式並行存取 (Optimistic Concurrency) 執行 Update 和 Delete 作業。開放式並行存取是在多個使用者同時操作資料的情況下,保護變更不會遺失的資料庫策略。當執行更新和刪除作業時,SqlDataSource 控制項會藉由 ConflictDetection 屬性判斷要使用那種層級的開放式並行存取檢查。

根據預設,ConflictDetection 屬性會設定為 ConflictOptions.OverwriteChanges,表示更新作業會覆寫資料錄中現有的任何值,而不會判斷其他來源是否曾修改資料錄。這個案例有時稱為 "last writer wins"。

您可以將 ConflictDetection 屬性設定為 ConflictOptions.CompareAllValues,以確定 SqlDataSource 控制項在 Update 或 Delete 命令期間包含所有原始值。這可以讓您的程式控制如果資料庫中的目前資料不符最初從資料庫所讀取的資料時,就不會執行 Update 作業的 SQL 陳述式。如需範例,請參閱開放式並行存取 (ADO.NET)。您可以處理 Updated 事件以檢查更新作業影響的資料錄數量;如果並未更新任何資料錄,就會發生並行違規。

請參閱

概念

SqlDataSource Web 伺服器控制項概觀