次の方法で共有


方法: Windows フォーム DataGrid コントロールを使用して入力を検証する

DataGridView コントロールは、DataGrid コントロールに代わって機能を追加します。ただし、DataGrid コントロールは、下位互換性と将来の使用の両方で保持されます (選択した場合)。 詳細については、「Windows フォーム DataGridView コントロールと DataGrid コントロールの違い」を参照してください。

Windows フォーム DataGrid コントロールでは、2 種類の入力検証を使用できます。 ユーザーがセルの許容できないデータ型 (文字列など) の値を整数に入力しようとすると、新しい無効な値が古い値に置き換えられます。 この種の入力検証は自動的に行われ、カスタマイズすることはできません。

他の種類の入力検証は、1以上でなければならないフィールドに0が入力されている場合や、不適切な文字列など、許容できないデータを拒否するために使用できます。 これは、ColumnChanging または RowChanging イベントのイベント ハンドラーを記述することによって、データセットで行われます。 次の例では、特に "Product" 列に対して許容できない値が許可されていないため、ColumnChanging イベントを使用しています。 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);
    

こちらも参照ください