次の方法で共有


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

注意

DataGridView コントロールは、DataGrid コントロールに代わると共に追加の機能を提供します。ただし、DataGrid コントロールは、下位互換性を保つ目的および将来使用する目的で保持されます。 詳細については、「Windows フォームの DataGridView コントロールと DataGrid コントロールの違いについて」を参照してください。

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

もう 1 つの種類の入力検証では、許可されないデータを拒否することができます (たとえば、1 以上である必要があるフィールドに 0 の値が入力された場合や、不適切な文字列が入力された場合など)。 これは、ColumnChanging イベントまたは RowChanging イベントのイベント ハンドラーを記述することで、データ セット内で実行されます。 次の例では、ColumnChanging イベントを使用してます。これは、"Product" 列に対して許可されない値を拒否するためです。 RowChanging イベントを使用して、"終了日" 列の値が、同じ行の "開始日" 列よりも後の値であるかどうかを確認することもできます。

ユーザー入力を検証するには

  1. 適切なテーブルの ColumnChanging イベントを処理するコードを記述します。 不適切な入力が検出された場合は、DataRow オブジェクトの SetColumnError メソッドを呼び出します。

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

関連項目