用 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);