共用方式為


如何:使用 Windows Form DataGrid 控制項驗證輸入

注意

DataGridView 控制項會取代 DataGrid 控制項並加入其他功能,不過您也可以選擇保留 DataGrid 控制項,以提供回溯相容性及未來使用。 如需詳細資訊,請參閱 Windows Forms DataGridView 和 DataGrid 控制項之間的差異

Windows Form DataGrid 控制項有兩種類型的輸入驗證可供使用。 如果使用者嘗試輸入儲存格的資料類型為不可接受的值,例如字串到整數中,新的無效值會取代為舊值。 這種輸入驗證會自動完成,而且無法自訂。

其他類型的輸入驗證可用來拒絕任何不可接受的資料,例如欄位中必須大於或等於 1 的 0 值,或是不適當的字串。 這會藉由撰寫 或 RowChanging 事件的事件處理常式,在 ColumnChanging 資料集中完成。 下列範例會使用 ColumnChanging 事件,因為「Product」資料行特別不允許無法接受的值。 您可以使用 RowChanging 事件來檢查 「End Date」 資料行的值是否晚于相同資料列中的 [開始日期] 資料行。

驗證使用者輸入

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

另請參閱