datagrid|window|控制項 Windows 表單 DataGrid 控制項驗證輸入
Windows 表單 DataGrid 控制項有兩種可用的輸入驗證類型。如果使用者試圖輸入一個值,而該值具有儲存格不可接受的資料類型(例如,向需要整數的儲存格中輸入一個字串),則新的無效值將替換為舊值。這種輸入驗證是自動完成的,不能進行自訂。
另一種的輸入驗證可用於拒絕任何不可接受的資料,例如,在必須大於或等於 1 的欄位中輸入 0,或者一個不合適的字串。這是在資料集中通過編寫 DataTable.ColumnChanging 或 DataTable.RowChanging 事件的事件處理常式來完成的。以下樣本使用 ColumnChanging 事件,因為“Product”列特別不允許不可接受的值。您可以使用 RowChanging 事件來檢查“End Date”列的值是否晚於同一行中“Start Date”的值。
驗證使用者輸入
1. 編寫代碼以處理相應表的 ColumnChanging 事件。當檢測到不適當的輸入時,調用 DataRow 對象的 SetColumnError 方法。
2. ' Visual Basic
3. Private Sub Customers_ColumnChanging(ByVal sender As Object, _
4. ByVal e As System.Data.DataColumnChangeEventArgs)
5. ' Only check for errors in the Product column
6. If (e.Column.ColumnName.Equals("Product")) Then
7. ' Do not allow "Automobile" as a product.
8. If CType(e.ProposedValue, String) = "Automobile" Then
9. Dim badValue As Object = e.ProposedValue
10. e.ProposedValue = "Bad Data"
11. e.Row.RowError = "The Product column contians an error"
12. e.Row.SetColumnError(e.Column, "Product cannot be " & _
13. CType(badValue, String))
14. End If
15. End If
16. End Sub
17.
18. // C#
19. //Handle column changing events on the Customers table
20. private void Customers_ColumnChanging(object sender, System.Data.DataColumnChangeEventArgs e) {
21.
22. //Only check for errors in the Product column
23. if (e.Column.ColumnName.Equals("Product")) {
24.
25. //Do not allow "Automobile" as a product
26. if (e.ProposedValue.Equals("Automobile")) {
27. object badValue = e.ProposedValue;
28. e.ProposedValue = "Bad Data";
29. e.Row.RowError = "The Product column contains an error";
30. e.Row.SetColumnError(e.Column, "Product cannot be " + badValue);
31. }
32. }
}
33. 將事件處理常式串連到事件。
將以下代碼置於表單的 Load 事件或其建構函式內。
' Visual Basic
' Assumes the grid is bound to a dataset called customersDataSet1
' with a table called Customers.
' Put this code in the form's Load event or its constructor.
AddHandler customersDataSet1.Tables("Customers").ColumnChanging, AddressOf Customers_ColumnChanging
// C#
// Assumes the grid is bound to a dataset called customersDataSet1
// with a table called Customers.
// Put this code in the form's Load event or its constructor.
customersDataSet1.Tables["Customers"].ColumnChanging += new DataColumnChangeEventHandler(this.Customers_ColumnChanging);