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);
新聞熱點
疑難解答