開放式並發可防止多使用者同時編輯導致資料遺失。本教程示範在 SqlDataSource 中啟用此功能。
使用者 A、B 同時編輯同一筆產品。A 修改名稱並更新,B 修改分類並更新。若無並發控制,B 的更新會覆蓋 A 的名稱變更。
UPDATE Products
SET ProductName = @ProductName, UnitPrice = @UnitPrice
WHERE ProductID = @original_ProductID
AND ProductName = @original_ProductName
AND UnitPrice = @original_UnitPrice
AND ... (所有其他欄位)
若資料庫中任一欄位已被他人修改,WHERE 條件不符,更新影響 0 列,SqlDataSource 會拋出 DBConcurrencyException。
<asp:GridView ID="GridView1" DataSourceID="SqlDataSource1"
OnRowUpdated="GridView1_RowUpdated" ... />
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
if (e.Exception != null && e.Exception is DBConcurrencyException)
{
e.ExceptionHandled = true;
lblError.Text = "資料已被其他人修改,請重新整理後再試。";
e.KeepInEditMode = true; // 保持編輯模式
}
}