型指定されたデータセットを用いてバインドする
DataGridViewコントロールが特によく使われるのは、データベースのテーブルをバインドするケースです。これを説明するために、現在のプロジェクトに型指定されたデータセットを追加します。Visual Studio 2005のソリューションエクスプローラでプロジェクト名を右クリックし、[追加]→[新しい項目の追加]を選択します。データセットテンプレートを選択し(DataSet1.xsdのデフォルトの名前を使用)、[追加]をクリックします。
サーバエクスプローラを起動し([表示]→[サーバエクスプローラ])、「Northwind」サンプルデータベースに移動します(SQL Server/SQL Server Expressでインストールされているものと仮定)。「Customers」テーブルをDataSet1.xsdのデザインサーフェイスにドラッグ&ドロップします。図5は、型指定されたデータセットを作成する様子を示しています。
次のステップには2つの選択肢があります。1つは、次に示すようにDataGridViewコントロールに「Customers」テーブルのテーブルアダプタを直接バインドする方法です。
'---create an instance of the table adapter--- Dim adapter As New CustomersTableAdapter '---data bind to the DataGridView control--- DataGridView1.DataSource = adapter.GetData
もう1つは、BindingSourceコントロールを使用する方法です。
'---create an instance of the table adapter--- Dim adapter As New CustomersTableAdapter '---create an instance of the bindingsource control--- Dim bindingSrc As New BindingSource '---set the datasource for the bindingsource control--- bindingSrc.DataSource = adapter.GetData '---data bind to the DataGridView control--- DataGridView1.DataSource = bindingSrc
なお、上のコードが正常に実行されるようにするためには、次のように名前空間をインポートしておく必要があります(DVGは、このプロジェクトの名前です)。
Imports DGV.DataSet1TableAdapters
図6は、このデータバインドの結果です。
データセットでバインドする
データセットを手動で作成する場合は、DataSourceプロパティにデータセットを設定し、表示するテーブルをDataMemberプロパティに指定すれば、DataGridViewコントロールにバインドできます。
Dim connStr As String = _ "Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;" & _ "Integrated Security=True" Dim sql As String = "SELECT * FROM Customers" Dim conn As SqlConnection = New SqlConnection(connStr) Dim comm As SqlCommand = New SqlCommand(sql, conn) Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm) Dim ds As DataSet = New DataSet() '---open the connection and fill the dataset--- conn.Open() '---fill the dataset--- dataadapter.Fill(ds, "Customers_table") '---close the connection--- conn.Close() '---bind to the DataGridView control--- DataGridView1.DataSource = ds '---set the table in the dataset to display--- DataGridView1.DataMember = "Customers_table"
クリックされたセルを検出する
ユーザーのクリックしたDataGridViewコントロール内のセルの値を取得する場合は、CellEnterイベントを処理します。
'---when the user clicks on the datagridview control--- Private Sub DataGridView1_CellEnter( _ ByVal sender As Object, _ ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _ Handles DataGridView1.CellEnter '---prints the content of the cell--- Console.WriteLine( _ DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value) End Sub
RowIndexプロパティとColumnIndexプロパティに、現在選択されているセルの行番号と列番号がそれぞれ設定されます。


