摘要
一般執行新增/修改完畢准備異動數據庫前通常會做一層數據正確性檢查的動作當我們使用 GridView 系結 SqlDataSoruce 來呈現數據若 GridView 進行數據編輯存盤前也要做字段值的檢查應該在如何做呢應該在那個控件的那個事件去處理這個檢查動作呢
程序說明及實作
首先在頁面上放置一個 GridView 及 SqlDataSource 控件GridView 設為可編輯狀態


當 GridView 編輯儲存時我們要先做一些字段值正確性的檢查動作以下的范例為測試示范只判斷 LastName 字段不得為空這種必填字段的判斷一般只要使用 RequiredFieldValidator 控件在 Client 端即可
方法一在 GridView 的 RowUpdating 事件處理字段檢查
GridView 在編輯儲存前會引發 RowUpdating 事件我們可以在此事件中處理字段檢查字段檢查的程序代碼如下當字段檢查不合法時設定 eCancel = True 即可中斷數據更新的動作執行程序故意將 LastName 清空然後按 [更新] 鈕進行儲存字段檢查的動作就被執行了

方法二在 SqlDataSource 的 Updating 事件處理字段檢查
對於 SqlDataSource 來說編輯數據異動數據庫之前會引發 SqlDataSource 的 Updating 事件
字段檢查的程序代碼如下當字段檢查不合法時設定 eCancel = True 即可中斷數據更新的動作這種方式的執行結果跟上個作法一樣


Protected Sub GridView
_RowUpdating()Sub GridView
_RowUpdating(ByVal sender As Object
ByVal e As System
Web
UI
WebControls
GridViewUpdateEventArgs) Handles GridView
RowUpdating

Dim sScript As String


If String
IsNullOrEmpty(e
NewValues
Item(
LastName
)) Then

sScript =
alert(
LastName 欄位不得為空
)

Me
ClientScript
RegisterStartupScript(Me
GetType
error
sScript
True)

e
Cancel = True

End If

End Sub
From:http://tw.wingwit.com/Article/program/net/201311/13964.html