次の方法で共有


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

基になるデータ ストアからのエラーの処理は、データ入力アプリケーションに必要な機能です。 Windows フォーム DataGridView コントロールは、データ ストアが制約違反または破損したビジネス ルールを検出したときに発生する DataError イベントを公開することで、これを簡単にします。

このチュートリアルでは、Northwind サンプル データベースの Customers テーブルから行を取得し、 DataGridView コントロールに表示します。 新しい行または編集された既存の行で重複する CustomerID 値が検出されると、 DataError イベントが発生します。これは、例外を説明する MessageBox を表示することによって処理されます。

このトピックのコードを 1 つのリストとしてコピーするには、「 方法: Windows フォーム DataGridView コントロールのデータ入力中に発生するエラーを処理する」を参照してください。

[前提条件]

このチュートリアルを完了するには、次のものが必要です。

  • Northwind SQL Server サンプル データベースを持つサーバーへのアクセス。

フォームの作成

DataGridView コントロールでデータ入力エラーを処理するには

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

    次のコード例では、基本的な初期化を提供し、 Main メソッドを含みます。

    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);
        }
    
    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)
    
        End Sub
    
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    }
    
        <STAThread()> _
        Shared Sub Main()
            Application.EnableVisualStyles()
            Application.Run(New Form1())
        End Sub
    
    End Class
    
  2. データベースへの接続の詳細を処理するためのメソッドをフォームのクラス定義に実装します。

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

    重要

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

    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, including the
        // schema information that contains the CustomerID column
        // constraint.
        SqlDataAdapter adapter =
            new SqlDataAdapter(selectCommand, connectionString);
        DataTable data = new DataTable();
        data.Locale = System.Globalization.CultureInfo.InvariantCulture;
        adapter.Fill(data);
        adapter.FillSchema(data, SchemaType.Source);
    
        return data;
    }
    
    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, including the 
        ' schema information that contains the CustomerID column 
        ' constraint.
        Dim adapter As New SqlDataAdapter(selectCommand, connectionString)
        Dim data As New DataTable()
        data.Locale = System.Globalization.CultureInfo.InvariantCulture
        adapter.Fill(data)
        adapter.FillSchema(data, SchemaType.Source)
    
        Return data
    
    End Function
    
  3. フォームのLoadイベントのハンドラーを実装して、DataGridViewBindingSourceを初期化し、データバインディングを設定します。

    private void Form1_Load(System.Object sender, System.EventArgs e)
    {
        // Attach the DataError event to the corresponding event handler.
        this.dataGridView1.DataError +=
            new DataGridViewDataErrorEventHandler(dataGridView1_DataError);
    
        // Initialize the BindingSource and bind the DataGridView to it.
        bindingSource1.DataSource = GetData("select * from Customers");
        this.dataGridView1.DataSource = bindingSource1;
        this.dataGridView1.AutoResizeColumns(
            DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
    }
    
    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
    
  4. DataErrorDataGridView イベントを処理します。

    エラーのコンテキストがコミット操作である場合は、 MessageBoxにエラーを表示します。

    private void dataGridView1_DataError(object sender,
        DataGridViewDataErrorEventArgs e)
    {
        // If the data source raises an exception when a cell value is
        // commited, display an error message.
        if (e.Exception != null &&
            e.Context == DataGridViewDataErrorContexts.Commit)
        {
            MessageBox.Show("CustomerID value must be unique.");
        }
    }
    
    Private Sub dataGridView1_DataError(ByVal sender As Object, _
        ByVal e As DataGridViewDataErrorEventArgs) _
        Handles dataGridView1.DataError
    
        ' If the data source raises an exception when a cell value is 
        ' commited, display an error message.
        If e.Exception IsNot Nothing AndAlso _
            e.Context = DataGridViewDataErrorContexts.Commit Then
    
            MessageBox.Show("CustomerID value must be unique.")
    
        End If
    
    End Sub
    

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

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

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

  • F5 キーを押してアプリケーションを実行します。

    Customers テーブルのデータが入力された DataGridView コントロールが表示されます。 CustomerIDに重複する値を入力して編集をコミットすると、セルの値は自動的に戻り、データ入力エラーを表示するMessageBoxが表示されます。

次のステップ

このアプリケーションは、DataGridView コントロールの機能の基本的な理解を提供します。 DataGridView コントロールの外観と動作は、いくつかの方法でカスタマイズできます。

こちらも参照ください