次の方法で共有


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

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

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

このトピックのコードを単一のリストとしてコピーするには、「方法 : 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)
    
        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);
        }
    
    
    ...
    
    
        [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, 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
    
    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;
    }
    
  3. フォームの Load イベントのハンドラーを実装します。このハンドラーで、DataGridViewBindingSource を初期化し、データ バインディングを設定します。

    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 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);
    }
    
  4. DataGridViewDataError イベントを処理します。

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

    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
    
    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.");
        }
    }
    

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

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

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

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

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

次の手順

このアプリケーションでは、DataGridView コントロールの基本的な機能を学ぶことができます。 次のような方法を使用すると、DataGridView コントロールの外観および動作をカスタマイズできます。

参照

処理手順

方法 : Windows フォーム DataGridView コントロールでのデータ入力中に発生したエラーを処理する

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

参照

DataGridView

BindingSource

概念

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

その他の技術情報

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