前回の記事「SQL Serverからデータを取得してDataGridViewに表示する(その1)」ではDataGridViewに表示するだけでしたが、今回はDataGridViewとBindingNavigatorを連動させます。
BindingNavigatorを使うことで、どのレコードを参照しているのかが分り易いです。
事前準備で、以下のオブジェクトをフォーム上にセットします。
・Button1
・BindingSource1
・BindingNavigator1
・DataGridView1
・DataSet1
DataSet1を追加する際、「型指定のないデータセット」を選択します。
以下のコードをコピペします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
Public Class Form1 Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click Dim My_TBL As String = Nothing Dim My_DBN As String = Nothing Dim My_SQL As String = Nothing Dim My_DST As DataSet = DataSet1 Dim My_DGV As DataGridView = DataGridView1 Dim My_BDN As BindingNavigator = BindingNavigator1 Dim My_BDS As BindingSource = BindingSource1 'DataSet内に作るDataTableの名前 'DataGridViewと同じ名前にすると使い回しする際、分かりやすい My_TBL = "TestTable001" 'SQLServerのデーターベース名 My_DBN = "TestDB" 'SQLServerに問い合わせするクエリ My_SQL = "SELECT TOP 15 * FROM SUG_PriceTrends_T" SQLDB_TO_DGV_BNV_DATASETs(My_SQL, My_DGV, My_BDN, My_BDS, My_DST, My_TBL, My_DBN) End Sub Public Sub SQLDB_TO_DGV_BNV_DATASETs(ByVal My_SQL As String, ByVal My_DGV As DataGridView, ByVal My_BNV As BindingNavigator, ByVal My_BDS As BindingSource, ByVal My_DtSet As DataSet, ByVal My_Table As String, ByVal My_DB As String) Try Dim con = New System.Data.SqlClient.SqlConnection() '------ Windows認証を利用して接続 ------ con.ConnectionString = _ "Data Source = USER-PC\AAASQLEXPRESS" & _ ";Initial Catalog = " & My_DB & _ ";Integrated Security = SSPI" & _ ";Connection Timeout=30;" '------ SQL Server認証で接続 ------ 'con.ConnectionString = _ ' "Data Source = USER-PC\AAASQLEXPRESS" & _ ' ";Initial Catalog = " & My_DB & _ ' ";uid = " & My_User & _ ' ";pwd = " & My_Pass & _ ' ";Connection Timeout=30;" con.Open() My_BDS.DataSource = Nothing My_BDS.DataMember = Nothing My_DGV.DataSource = Nothing My_BNV.BindingSource = Nothing For i = 0 To My_DtSet.Tables.Count - 1 If My_DtSet.Tables(i).TableName = My_Table Then My_DtSet.Tables.Remove(My_Table) Exit For End If Next Dim Sqlda As New SqlClient.SqlDataAdapter Sqlda.SelectCommand = New SqlClient.SqlCommand(My_SQL, con) Sqlda.SelectCommand.CommandTimeout = 0 Sqlda.Fill(My_DtSet, My_Table) For i = 0 To My_DtSet.Tables.Count - 1 If My_DtSet.Tables(i).TableName = My_Table Then My_BDS.DataSource = My_DtSet My_BDS.DataMember = My_Table My_DGV.DataSource = My_BDS My_BNV.BindingSource = My_BDS Exit For End If Next con.Close() con.Dispose() Catch ex As Exception MessageBox.Show(ex.ToString) End Try End Sub End Class |
Button1をクリックすると下図の様にBindingNavigator1のレコードの番号がDataGridView1の選択行とリンクします。
また、ナビゲータの各ボタンで移動できます。
次回は、DataSetのテーブル内容をExcel出力する方法を紹介します。