次の方法で共有


チュートリアル : Windows フォーム DataGridView コントロールのデータの妥当性検査

更新 : 2007 年 11 月

データ入力機能をユーザーに表示する場合、フォームに入力されたデータの妥当性検査を行うことが必要になる場合があります。DataGridView クラスには、データがデータ ストアにコミットされる前に妥当性検査を実行できる便利な手段が用意されています。現在のセルが変更されたときに DataGridView で発生する CellValidating イベントを処理することで、データの妥当性検査を行うことができます。

このチュートリアルでは、Northwind サンプル データベースの Customers テーブルから行を取得し、DataGridView コントロールに表示します。ユーザーが CompanyName 列のセルを編集し、そのセルから離れようとすると、CellValidating イベント ハンドラは新しい会社名文字列が空でないかどうかを確認し、新しい値が空の文字列の場合、DataGridView は空でない文字列が入力されるまで、ユーザーのカーソルがそのセルから移動できないようにします。

このトピックのコードを単一のリストとしてコピーするには、「方法 : Windows フォーム DataGridView コントロールのデータを検証する」を参照してください。

前提条件

このチュートリアルを実行するための要件は次のとおりです。

  • Northwind SQL Server サンプル データベースがあるサーバーへのアクセス

フォームの作成

DataGridView に入力されたデータの妥当性検査を行うには

  1. Form から派生し、DataGridView コントロールおよび BindingSource コンポーネントを含むクラスを作成します。

    次のコード例は、基本的な初期化処理を行い、Main メソッドを含みます。

    Imports System
    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.Windows.Forms
    
    Public Class Form1
        Inherits System.Windows.Forms.Form
    
        Private WithEvents dataGridView1 As New DataGridView()
        Private bindingSource1 As New BindingSource()
    
        Public Sub New()
    
            ' Initialize the form.
            Me.dataGridView1.Dock = DockStyle.Fill
            Me.Controls.Add(dataGridView1)
            Me.Text = "DataGridView validation demo (disallows empty CompanyName)"
    
        End Sub
    
    
    ...
    
    
        <STAThread()> _
        Shared Sub Main()
            Application.EnableVisualStyles()
            Application.Run(New Form1())
        End Sub
    
    End Class
    
    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Windows.Forms;
    
    public class Form1 : System.Windows.Forms.Form
    {
        private DataGridView dataGridView1 = new DataGridView();
        private BindingSource bindingSource1 = new BindingSource();
    
        public Form1()
        {
            // Initialize the form.
            this.dataGridView1.Dock = DockStyle.Fill;
            this.Controls.Add(dataGridView1);
            this.Load += new EventHandler(Form1_Load);
            this.Text = "DataGridView validation demo (disallows empty CompanyName)";
        }
    
    
    ...
    
    
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    
    }
    
  2. フォームのクラス定義に、データベースへの接続の詳細を処理するメソッドを実装します。

    このコード例では、データが入力された DataTable オブジェクトを返す GetData メソッドを使用します。connectionString 変数には、使用するデータベースに適した値を設定してください。

    セキュリティに関するメモ :

    接続文字列内にパスワードなどの機密情報を格納すると、アプリケーションのセキュリティに影響を及ぼすことがあります。データベースへのアクセスを制御する方法としては、Windows 認証 (統合セキュリティとも呼ばれます) を使用する方が安全です。詳細については、「接続情報の保護 (ADO.NET)」を参照してください。

    Private Shared Function GetData(ByVal selectCommand As String) As DataTable
    
        Dim connectionString As String = _
            "Integrated Security=SSPI;Persist Security Info=False;" + _
            "Initial Catalog=Northwind;Data Source=localhost;Packet Size=4096"
    
        ' Connect to the database and fill a data table.
        Dim adapter As New SqlDataAdapter(selectCommand, connectionString)
        Dim data As New DataTable()
        data.Locale = System.Globalization.CultureInfo.InvariantCulture
        adapter.Fill(data)
    
        Return data
    
    End Function
    
    private static DataTable GetData(string selectCommand)
    {
        string connectionString =
            "Integrated Security=SSPI;Persist Security Info=False;" +
            "Initial Catalog=Northwind;Data Source=localhost;Packet Size=4096";
    
        // Connect to the database and fill a data table.
        SqlDataAdapter adapter =
            new SqlDataAdapter(selectCommand, connectionString);
        DataTable data = new DataTable();
        data.Locale = System.Globalization.CultureInfo.InvariantCulture;
        adapter.Fill(data);
    
        return data;
    }
    
  3. DataGridViewBindingSource の初期化、およびデータ バインディングの設定を行うために、フォームの Load イベントのハンドラを実装します。

    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Me.Load
    
        ' Initialize the BindingSource and bind the DataGridView to it.
        bindingSource1.DataSource = GetData("select * from Customers")
        Me.dataGridView1.DataSource = bindingSource1
        Me.dataGridView1.AutoResizeColumns( _
            DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)
    
    End Sub
    
    private void Form1_Load(System.Object sender, System.EventArgs e)
    {
        // Attach DataGridView events to the corresponding event handlers.
        this.dataGridView1.CellValidating += new
            DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);
        this.dataGridView1.CellEndEdit += new
            DataGridViewCellEventHandler(dataGridView1_CellEndEdit);
    
        // Initialize the BindingSource and bind the DataGridView to it.
        bindingSource1.DataSource = GetData("select * from Customers");
        this.dataGridView1.DataSource = bindingSource1;
        this.dataGridView1.AutoResizeColumns(
            DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
    }
    
  4. DataGridView コントロールの CellValidating イベントおよび CellEndEdit イベントのハンドラを実装します。

    CellValidating イベント ハンドラでは、CompanyName 列のセルの値が空であるかどうかを調べます。セルの値が妥当性検査に合格しなかった場合は、System.Windows.Forms.DataGridViewCellValidatingEventArgs クラスの Cancel プロパティを true に設定します。これにより、DataGridView コントロールはカーソルがそのセルから移動することを禁止します。その行の ErrorText プロパティに説明文字列を設定します。これにより、エラー アイコンと、エラー テキストを含むツールヒントが表示されます。CellEndEdit イベント ハンドラでは、行の ErrorText プロパティに空の文字列を設定します。CellEndEdit イベントは、セルの編集モードが終了した場合にのみ発生します。そのためには、セルが妥当性検査に合格することが必要です。

    Private Sub dataGridView1_CellValidating(ByVal sender As Object, _
        ByVal e As DataGridViewCellValidatingEventArgs) _
        Handles dataGridView1.CellValidating
    
        ' Validate the CompanyName entry by disallowing empty strings.
        If dataGridView1.Columns(e.ColumnIndex).Name = "CompanyName" Then
            If e.FormattedValue IsNot Nothing AndAlso _
                String.IsNullOrEmpty(e.FormattedValue.ToString()) Then
    
                dataGridView1.Rows(e.RowIndex).ErrorText = _
                    "Company Name must not be empty"
                e.Cancel = True
    
            End If
        End If
    
    End Sub
    
    Private Sub dataGridView1_CellEndEdit(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _
        Handles dataGridView1.CellEndEdit
    
        ' Clear the row error in case the user presses ESC.   
        dataGridView1.Rows(e.RowIndex).ErrorText = String.Empty
    
    End Sub
    
    private void dataGridView1_CellValidating(object sender,
        DataGridViewCellValidatingEventArgs e)
    {
        // Validate the CompanyName entry by disallowing empty strings.
        if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
        {
            if (e.FormattedValue == null && 
                String.IsNullOrEmpty(e.FormattedValue.ToString()))
            {
                dataGridView1.Rows[e.RowIndex].ErrorText =
                    "Company Name must not be empty";
                e.Cancel = true;
            }
        }
    }
    
    void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        // Clear the row error in case the user presses ESC.   
        dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty;
    }
    

アプリケーションのテスト

フォームをテストして、期待どおりに動作することを確認します。

フォームをテストするには

  • アプリケーションをコンパイルして実行します。

    DataGridView に、Customers テーブルからのデータが入力されて表示されます。CompanyName 列内のセルをダブルクリックすると、値を編集できます。すべての文字を削除してから、Tab キーを押してそのセルから離れようとすると、DataGridView によって阻止されます。空でない文字列をセルに入力すると、DataGridView コントロールはセルから離れることを許可します。

次の手順

このアプリケーションは、DataGridView コントロールの機能に関する基本事項を理解するのに役立ちます。DataGridView コントロールの動作と外観は、次のようなさまざまな方法でカスタマイズできます。

参照

処理手順

方法 : Windows フォーム DataGridView コントロールのデータを検証する

チュートリアル : Windows フォーム DataGridView コントロールでのデータ入力中に発生したエラーの処理

概念

接続情報の保護 (ADO.NET)

参照

DataGridView

BindingSource

その他の技術情報

Windows フォーム DataGridView コントロールでのデータ入力