如何:用 Windows 窗体 DataGrid 控件验证输入

注释

DataGridView 控件替换并添加 DataGrid 控件的功能;但是,如果选择,则保留 DataGrid 控件以实现后向兼容性和将来使用。 有关详细信息,请参阅 Windows 窗体 DataGridView 控件与 DataGrid 控件之间的区别

Windows 窗体 DataGrid 控件有两种类型的输入验证可用。 如果用户尝试输入单元格不可接受的数据类型的值(例如将字符串转换为整数),则新的无效值将替换为旧值。 这种输入验证是自动完成的,无法自定义。

其他类型的输入验证可用于拒绝任何不可接受的数据,例如,字段中必须大于或等于 1 的 0 值,或者不适当的字符串。 此操作通过在数据集中为 ColumnChangingRowChanging 事件编写事件处理程序来完成。 下面的示例使用 ColumnChanging 事件,因为“Product”列尤其不允许使用不可接受的值。 可以使用 RowChanging 事件来检查“结束日期”列的值是否晚于同一行中的“开始日期”列。

验证用户输入

  1. 编写代码来处理相应表的 ColumnChanging 事件。 检测到不适当的输入时,调用 SetColumnError 对象的 DataRow 方法。

    Private Sub Customers_ColumnChanging(ByVal sender As Object, _
    ByVal e As System.Data.DataColumnChangeEventArgs)
       ' Only check for errors in the Product column
       If (e.Column.ColumnName.Equals("Product")) Then
          ' Do not allow "Automobile" as a product.
          If CType(e.ProposedValue, String) = "Automobile" Then
             Dim badValue As Object = e.ProposedValue
             e.ProposedValue = "Bad Data"
             e.Row.RowError = "The Product column contains an error"
             e.Row.SetColumnError(e.Column, "Product cannot be " & _
             CType(badValue, String))
          End If
       End If
    End Sub
    
    //Handle column changing events on the Customers table
    private void Customers_ColumnChanging(object sender, System.Data.DataColumnChangeEventArgs e) {
    
       //Only check for errors in the Product column
       if (e.Column.ColumnName.Equals("Product")) {
    
          //Do not allow "Automobile" as a product
          if (e.ProposedValue.Equals("Automobile")) {
             object badValue = e.ProposedValue;
             e.ProposedValue = "Bad Data";
             e.Row.RowError = "The Product column contains an error";
             e.Row.SetColumnError(e.Column, "Product cannot be " + badValue);
          }
       }
    }
    
  2. 将事件处理程序连接到事件。

    将以下代码置于窗体的 Load 事件或其构造函数中。

    ' 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
    
    // 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);
    

另请参阅