方法: DataView オブジェクトを Windows フォーム DataGridView コントロールにバインドする

DataGridView コントロールには、データを表形式で表示するための強力で柔軟な機能が用意されています。 DataGridView コントロールは、標準 Windows フォーム データ バインディング モデルをサポートするため、DataView およびその他の各種のデータ ソースにバインドします。 ただし、ほとんどの状況では、データ ソースとの対話の詳細を管理する BindingSource コンポーネントにバインドします。

DataGridView コントロールについて詳しくは、「DataGridView コントロールの概要」をご覧ください。

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

  1. データベースからデータを取得する操作の詳細を処理するメソッドを実装します。 次のコード例では、GetData コンポーネントを初期化する SqlDataAdapter メソッドを実装し、これを使用して DataSet に値を設定します。 connectionString 変数は、使用しているデータベースに合った値に設定してください。 AdventureWorks SQL Server サンプル データベースがインストールされているサーバーにアクセスする必要があります。

    void GetData()
    {
        try
        {
            // Initialize the DataSet.
            _dataSet = new DataSet
            {
                Locale = CultureInfo.InvariantCulture
            };
    
            // Create the connection string for the AdventureWorks sample database.
            const string connectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;"
                + "Integrated Security=true;";
    
            // Create the command strings for querying the Contact table.
            const string contactSelectCommand = "SELECT ContactID, Title, FirstName, LastName, EmailAddress, Phone FROM Person.Contact";
    
            // Create the contacts data adapter.
            _contactsDataAdapter = new SqlDataAdapter(
                contactSelectCommand,
                connectionString);
    
            // Create a command builder to generate SQL update, insert, and
            // delete commands based on the contacts select command. These are used to
            // update the database.
            var contactsCommandBuilder = new SqlCommandBuilder(_contactsDataAdapter);
    
            // Fill the data set with the contact information.
            _contactsDataAdapter.Fill(_dataSet, "Contact");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    
    Private Sub GetData()
        Try
            ' Initialize the DataSet.
            dataSet = New DataSet()
            dataSet.Locale = CultureInfo.InvariantCulture
    
            ' Create the connection string for the AdventureWorks sample database.
            Dim connectionString As String = "Data Source=localhost;Initial Catalog=AdventureWorks;" _
                    & "Integrated Security=true;"
    
            ' Create the command strings for querying the Contact table.
            Dim contactSelectCommand As String = "SELECT ContactID, Title, FirstName, LastName, EmailAddress, Phone FROM Person.Contact"
    
            ' Create the contacts data adapter.
            contactsDataAdapter = New SqlDataAdapter( _
                contactSelectCommand, _
                connectionString)
    
            ' Create a command builder to generate SQL update, insert, and
            ' delete commands based on the contacts select command. These are used to
            ' update the database.
            Dim contactsCommandBuilder As SqlCommandBuilder = New SqlCommandBuilder(contactsDataAdapter)
    
            ' Fill the data set with the contact information.
            contactsDataAdapter.Fill(dataSet, "Contact")
    
        Catch ex As SqlException
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    
  2. フォームの Load イベント ハンドラーで、DataGridView コントロールを BindingSource コンポーネントにバインドし、GetData メソッドを呼び出してデータベースからデータを取得します。 DataView は、Contact DataTable に対する LINQ to DataSet クエリから作成された後、BindingSource コンポーネントにバインドされます。

    void Form1_Load(object sender, EventArgs e)
    {
        // Connect to the database and fill the DataSet.
        GetData();
    
        contactDataGridView.DataSource = contactBindingSource;
    
        // Create a LinqDataView from a LINQ to DataSet query and bind it
        // to the Windows forms control.
        EnumerableRowCollection<DataRow> contactQuery = from row in _dataSet.Tables["Contact"].AsEnumerable()
                                                        where row.Field<string>("EmailAddress") != null
                                                        orderby row.Field<string>("LastName")
                                                        select row;
    
        _contactView = contactQuery.AsDataView();
    
        // Bind the DataGridView to the BindingSource.
        contactBindingSource.DataSource = _contactView;
        contactDataGridView.AutoResizeColumns();
    }
    
    Private Sub Form1_Load(ByVal sender As System.Object, _
                           ByVal e As System.EventArgs) _
                           Handles MyBase.Load
        ' Connect to the database and fill the DataSet.
        GetData()
    
        contactDataGridView.DataSource = contactBindingSource
    
        ' Create a LinqDataView from a LINQ to DataSet query and bind it 
        ' to the Windows forms control.
        Dim contactQuery = _
            From row In dataSet.Tables("Contact").AsEnumerable() _
            Where row.Field(Of String)("EmailAddress") <> Nothing _
            Order By row.Field(Of String)("LastName") _
            Select row
    
        contactView = contactQuery.AsDataView()
    
        ' Bind the DataGridView to the BindingSource.
        contactBindingSource.DataSource = contactView
        contactDataGridView.AutoResizeColumns()
    End Sub
    

関連項目