次の方法で共有


方法 : データを Windows フォーム DataGridView コントロールにバインドする

DataGridView コントロールは、標準の Windows フォーム データ バインディング モデルをサポートしているため、さまざまなデータ ソースにバインドできます。 ただし、通常は、データ ソースとの対話の詳細を管理する BindingSource コンポーネントにバインドします。 BindingSource コンポーネントは、任意の Windows フォーム データ ソースを表すことができ、データの場所を柔軟に選択または変更できるようにします。 DataGridView コントロールでサポートされているデータ ソースの詳細については、「DataGridView コントロールの概要 (Windows フォーム)」を参照してください。

Visual Studio では、このタスクに対する広範なサポートが用意されています。 詳細については 方法 : デザイナを使用してデータを Windows フォーム DataGridView コントロールにバインドする および 方法 : デザイナを使用してデータを Windows フォーム DataGridView コントロールにバインドする および 方法 : デザイナを使用してデータを Windows フォーム DataGridView コントロールにバインドする および 方法 : デザイナーを使用してデータを Windows フォーム DataGridView コントロールにバインドする.

手順

DataGridView コントロールをデータに接続するには

  1. データベースからデータを取得する詳細な手順を処理するメソッドを実装します。 次のコード例では、SqlDataAdapter コンポーネントを初期化する GetData メソッドを実装して、DataTable にデータを読み込みます。 その後、DataTableBindingSource コンポーネントにバインドされます。 connectionString 変数には、データベースに適した値を設定してください。 Northwind SQL Server サンプル データベースがインストールされているサーバーにアクセスする必要があります。

    Private Sub GetData(ByVal selectCommand As String)
    
        Try
            ' Specify a connection string. Replace the given value with a 
            ' valid connection string for a Northwind SQL Server sample
            ' database accessible to your system.
            Dim connectionString As String = _
                "Integrated Security=SSPI;Persist Security Info=False;" + _
                "Initial Catalog=Northwind;Data Source=localhost"
    
            ' Create a new data adapter based on the specified query.
            Me.dataAdapter = New SqlDataAdapter(selectCommand, connectionString)
    
            ' Create a command builder to generate SQL update, insert, and
            ' delete commands based on selectCommand. These are used to
            ' update the database.
            Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapter)
    
            ' Populate a new data table and bind it to the BindingSource.
            Dim table As New DataTable()
            table.Locale = System.Globalization.CultureInfo.InvariantCulture
            Me.dataAdapter.Fill(table)
            Me.bindingSource1.DataSource = table
    
            ' Resize the DataGridView columns to fit the newly loaded content.
            Me.dataGridView1.AutoResizeColumns( _
                DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)
        Catch ex As SqlException
            MessageBox.Show("To run this example, replace the value of the " + _
                "connectionString variable with a connection string that is " + _
                "valid for your system.")
        End Try
    
    End Sub
    
    private void GetData(string selectCommand)
    {
        try
        {
            // Specify a connection string. Replace the given value with a 
            // valid connection string for a Northwind SQL Server sample
            // database accessible to your system.
            String connectionString =
                "Integrated Security=SSPI;Persist Security Info=False;" +
                "Initial Catalog=Northwind;Data Source=localhost";
    
            // Create a new data adapter based on the specified query.
            dataAdapter = new SqlDataAdapter(selectCommand, connectionString);
    
            // Create a command builder to generate SQL update, insert, and
            // delete commands based on selectCommand. These are used to
            // update the database.
            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
    
            // Populate a new data table and bind it to the BindingSource.
            DataTable table = new DataTable();
            table.Locale = System.Globalization.CultureInfo.InvariantCulture;
            dataAdapter.Fill(table);
            bindingSource1.DataSource = table;
    
            // Resize the DataGridView columns to fit the newly loaded content.
            dataGridView1.AutoResizeColumns( 
                DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
        }
        catch (SqlException)
        {
            MessageBox.Show("To run this example, replace the value of the " +
                "connectionString variable with a connection string that is " +
                "valid for your system.");
        }
    }
    
    private:
        void GetData(String^ selectCommand)
        {
            try
            {
                // Specify a connection string. Replace the given value with a 
                // valid connection string for a Northwind SQL Server sample
                // database accessible to your system.
                String^ connectionString = 
                    "Integrated Security=SSPI;Persist Security Info=False;" +
                    "Initial Catalog=Northwind;Data Source=localhost";
    
                // Create a new data adapter based on the specified query.
                dataAdapter = gcnew SqlDataAdapter(selectCommand, connectionString);
    
                // Create a command builder to generate SQL update, insert, and
                // delete commands based on selectCommand. These are used to
                // update the database.
                gcnew SqlCommandBuilder(dataAdapter);
    
                // Populate a new data table and bind it to the BindingSource.
                DataTable^ table = gcnew DataTable();
                dataAdapter->Fill(table);
                bindingSource1->DataSource = table;
    
                // Resize the DataGridView columns to fit the newly loaded content.
                dataGridView1->AutoResizeColumns( 
                    DataGridViewAutoSizeColumnsMode::AllCellsExceptHeader);
            }
            catch (SqlException^)
            {
                MessageBox::Show("To run this example, replace the value of the " +
                    "connectionString variable with a connection string that is " +
                    "valid for your system.");
            }
        }
    
  2. フォームの Load イベント ハンドラーで、DataGridView コントロールを BindingSource コンポーネントにバインドし、GetData メソッドを呼び出してデータベースからデータを取得します。

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles Me.Load
    
        ' Bind the DataGridView to the BindingSource
        ' and load the data from the database.
        Me.dataGridView1.DataSource = Me.bindingSource1
        GetData("select * from Customers")
    
    End Sub
    
    private void Form1_Load(object sender, System.EventArgs e)
    {
        // Bind the DataGridView to the BindingSource
        // and load the data from the database.
        dataGridView1.DataSource = bindingSource1;
        GetData("select * from Customers");
    }
    
    void Form1_Load(Object^ /*sender*/, System::EventArgs^ /*e*/)
    {
        // Bind the DataGridView to the BindingSource
        // and load the data from the database.
        dataGridView1->DataSource = bindingSource1;
        GetData("select * from Customers");
    }
    

使用例

データベースからデータを再読み込みするためのボタンを提供し、変更をデータベースに送信する完全なコード例を次に示します。

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms

Public Class Form1
    Inherits System.Windows.Forms.Form

    Private dataGridView1 As New DataGridView()
    Private bindingSource1 As New BindingSource()
    Private dataAdapter As New SqlDataAdapter()
    Private WithEvents reloadButton As New Button()
    Private WithEvents submitButton As New Button()

    <STAThreadAttribute()> _
    Public Shared Sub Main()
        Application.Run(New Form1())
    End Sub

    ' Initialize the form.
    Public Sub New()

        Me.dataGridView1.Dock = DockStyle.Fill

        Me.reloadButton.Text = "reload"
        Me.submitButton.Text = "submit"

        Dim panel As New FlowLayoutPanel()
        panel.Dock = DockStyle.Top
        panel.AutoSize = True
        panel.Controls.AddRange(New Control() {Me.reloadButton, Me.submitButton})

        Me.Controls.AddRange(New Control() {Me.dataGridView1, panel})
        Me.Text = "DataGridView databinding and updating demo"

    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles Me.Load

        ' Bind the DataGridView to the BindingSource
        ' and load the data from the database.
        Me.dataGridView1.DataSource = Me.bindingSource1
        GetData("select * from Customers")

    End Sub

    Private Sub reloadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles reloadButton.Click

        ' Reload the data from the database.
        GetData(Me.dataAdapter.SelectCommand.CommandText)

    End Sub

    Private Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles submitButton.Click

        ' Update the database with the user's changes.
        Me.dataAdapter.Update(CType(Me.bindingSource1.DataSource, DataTable))

    End Sub

    Private Sub GetData(ByVal selectCommand As String)

        Try
            ' Specify a connection string. Replace the given value with a 
            ' valid connection string for a Northwind SQL Server sample
            ' database accessible to your system.
            Dim connectionString As String = _
                "Integrated Security=SSPI;Persist Security Info=False;" + _
                "Initial Catalog=Northwind;Data Source=localhost"

            ' Create a new data adapter based on the specified query.
            Me.dataAdapter = New SqlDataAdapter(selectCommand, connectionString)

            ' Create a command builder to generate SQL update, insert, and
            ' delete commands based on selectCommand. These are used to
            ' update the database.
            Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapter)

            ' Populate a new data table and bind it to the BindingSource.
            Dim table As New DataTable()
            table.Locale = System.Globalization.CultureInfo.InvariantCulture
            Me.dataAdapter.Fill(table)
            Me.bindingSource1.DataSource = table

            ' Resize the DataGridView columns to fit the newly loaded content.
            Me.dataGridView1.AutoResizeColumns( _
                DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)
        Catch ex As SqlException
            MessageBox.Show("To run this example, replace the value of the " + _
                "connectionString variable with a connection string that is " + _
                "valid for your system.")
        End Try

    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();
    private SqlDataAdapter dataAdapter = new SqlDataAdapter();
    private Button reloadButton = new Button();
    private Button submitButton = new Button();

    [STAThreadAttribute()]
    public static void Main()
    {
        Application.Run(new Form1());
    }

    // Initialize the form.
    public Form1()
    {
        dataGridView1.Dock = DockStyle.Fill;

        reloadButton.Text = "reload";
        submitButton.Text = "submit";
        reloadButton.Click += new System.EventHandler(reloadButton_Click);
        submitButton.Click += new System.EventHandler(submitButton_Click);

        FlowLayoutPanel panel = new FlowLayoutPanel();
        panel.Dock = DockStyle.Top;
        panel.AutoSize = true;
        panel.Controls.AddRange(new Control[] { reloadButton, submitButton });

        this.Controls.AddRange(new Control[] { dataGridView1, panel });
        this.Load += new System.EventHandler(Form1_Load);
        this.Text = "DataGridView databinding and updating demo";
    }

    private void Form1_Load(object sender, System.EventArgs e)
    {
        // Bind the DataGridView to the BindingSource
        // and load the data from the database.
        dataGridView1.DataSource = bindingSource1;
        GetData("select * from Customers");
    }

    private void reloadButton_Click(object sender, System.EventArgs e)
    {
        // Reload the data from the database.
        GetData(dataAdapter.SelectCommand.CommandText);
    }

    private void submitButton_Click(object sender, System.EventArgs e)
    {
        // Update the database with the user's changes.
        dataAdapter.Update((DataTable)bindingSource1.DataSource);
    }

    private void GetData(string selectCommand)
    {
        try
        {
            // Specify a connection string. Replace the given value with a 
            // valid connection string for a Northwind SQL Server sample
            // database accessible to your system.
            String connectionString =
                "Integrated Security=SSPI;Persist Security Info=False;" +
                "Initial Catalog=Northwind;Data Source=localhost";

            // Create a new data adapter based on the specified query.
            dataAdapter = new SqlDataAdapter(selectCommand, connectionString);

            // Create a command builder to generate SQL update, insert, and
            // delete commands based on selectCommand. These are used to
            // update the database.
            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

            // Populate a new data table and bind it to the BindingSource.
            DataTable table = new DataTable();
            table.Locale = System.Globalization.CultureInfo.InvariantCulture;
            dataAdapter.Fill(table);
            bindingSource1.DataSource = table;

            // Resize the DataGridView columns to fit the newly loaded content.
            dataGridView1.AutoResizeColumns( 
                DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
        }
        catch (SqlException)
        {
            MessageBox.Show("To run this example, replace the value of the " +
                "connectionString variable with a connection string that is " +
                "valid for your system.");
        }
    }

}
#using <System.Data.dll>
#using <System.Transactions.dll>
#using <System.EnterpriseServices.dll>
#using <System.Xml.dll>
#using <System.Drawing.dll>
#using <System.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Data;
using namespace System::Data::SqlClient;
using namespace System::Windows::Forms;

public ref class Form1 : public System::Windows::Forms::Form
{
private:
    DataGridView^ dataGridView1;
private:
    BindingSource^ bindingSource1;
private:
    SqlDataAdapter^ dataAdapter;
private:
    Button^ reloadButton;
private:
    Button^ submitButton;

public:
    static void Main()
    {
        Application::Run(gcnew Form1());
    }

    // Initialize the form.
public:
    Form1()
    {
        dataGridView1 = gcnew DataGridView();
        bindingSource1 = gcnew BindingSource();
        dataAdapter = gcnew SqlDataAdapter();
        reloadButton = gcnew Button();
        submitButton = gcnew Button();

        dataGridView1->Dock = DockStyle::Fill;

        reloadButton->Text = "reload";
        submitButton->Text = "submit";
        reloadButton->Click += gcnew System::EventHandler(this,&Form1::reloadButton_Click);
        submitButton->Click += gcnew System::EventHandler(this,&Form1::submitButton_Click);

        FlowLayoutPanel^ panel = gcnew FlowLayoutPanel();
        panel->Dock = DockStyle::Top;
        panel->AutoSize = true;
        panel->Controls->AddRange(gcnew array<Control^> { reloadButton, submitButton });

        this->Controls->AddRange(gcnew array<Control^> { dataGridView1, panel });
        this->Load += gcnew System::EventHandler(this,&Form1::Form1_Load);
    }

    void Form1_Load(Object^ /*sender*/, System::EventArgs^ /*e*/)
    {
        // Bind the DataGridView to the BindingSource
        // and load the data from the database.
        dataGridView1->DataSource = bindingSource1;
        GetData("select * from Customers");
    }

    void reloadButton_Click(Object^ /*sender*/, System::EventArgs^ /*e*/)
    {
        // Reload the data from the database.
        GetData(dataAdapter->SelectCommand->CommandText);
    }

    void submitButton_Click(Object^ /*sender*/, System::EventArgs^ /*e*/)
    {
        // Update the database with the user's changes.
        dataAdapter->Update((DataTable^)bindingSource1->DataSource);
    }

private:
    void GetData(String^ selectCommand)
    {
        try
        {
            // Specify a connection string. Replace the given value with a 
            // valid connection string for a Northwind SQL Server sample
            // database accessible to your system.
            String^ connectionString = 
                "Integrated Security=SSPI;Persist Security Info=False;" +
                "Initial Catalog=Northwind;Data Source=localhost";

            // Create a new data adapter based on the specified query.
            dataAdapter = gcnew SqlDataAdapter(selectCommand, connectionString);

            // Create a command builder to generate SQL update, insert, and
            // delete commands based on selectCommand. These are used to
            // update the database.
            gcnew SqlCommandBuilder(dataAdapter);

            // Populate a new data table and bind it to the BindingSource.
            DataTable^ table = gcnew DataTable();
            dataAdapter->Fill(table);
            bindingSource1->DataSource = table;

            // Resize the DataGridView columns to fit the newly loaded content.
            dataGridView1->AutoResizeColumns( 
                DataGridViewAutoSizeColumnsMode::AllCellsExceptHeader);
        }
        catch (SqlException^)
        {
            MessageBox::Show("To run this example, replace the value of the " +
                "connectionString variable with a connection string that is " +
                "valid for your system.");
        }
    }
};

コードのコンパイル

この例で必要な要素は次のとおりです。

  • System、System.Windows.Forms、System.Data、System.XML の各アセンブリへの参照。

Visual Basic または Visual C# のコマンド ラインからこの例をビルドする方法の詳細については、「コマンド ラインからのビルド (Visual Basic)」または「csc.exe を使用したコマンド ラインからのビルド」を参照してください。 Visual Studio で新しいプロジェクトにコードを貼り付けてこの例をビルドすることもできます。 詳細については 方法 : 完成した Windows フォーム コードの例を Visual Studio を使ってコンパイルして実行する および 方法 : 完成した Windows フォーム コードの例を Visual Studio を使ってコンパイルして実行する および 方法 : 完成した Windows フォーム コードの例を Visual Studio を使ってコンパイルして実行する および 方法 : 完成した Windows フォーム コードの例を Visual Studio を使ってコンパイルして実行する および 方法 : 完成した Windows フォーム コードの例を Visual Studio を使ってコンパイルして実行する.

セキュリティ

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

参照

参照

DataGridView

DataGridView.DataSource

BindingSource

概念

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

その他の技術情報

Windows フォーム DataGridView コントロールでのデータの表示