1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【VB.NET】データベースのデータをDataGridViewで表示する方法

Posted at

開発環境

Windows11
VisualStudio2019
VB.NET 4.7.2
MySQL 8.0.34

1.MySQLに接続する

Imports MySql.Data.MySqlClient
:
Try
    Dim builder = New MySqlConnectionStringBuilder()
    ' データベース接続に必要な情報をbuilderに与える
    builder.Server = "localhost"
    builder.Port = 3306
    builder.UserID = "ユーザー名"
    builder.Password = "パスワード"
    builder.Database = "データベース名"
    Dim conStr = builder.ToString()

    ' データベースに接続
    Dim con As New MySqlConnection
    con.ConnectionString = conStr
    con.Open()
Catch ex As Exception
    MessageBox.Show("エラーが発生しました。error:" & ex.Message)
End Try

2.データベースのデータを取得,DataGridViewに表示する

Dim sqlStr As String = "SELECT id AS ""ID"", subject AS ""科目"" FROM subject ORDER BY id"
Dim dt As DataTable
Dim adapter = New MySqlDataAdapter(sqlStr, con)            ' データ取得のためのアダプタ設定
Dim data As New DataSet
adapter.Fill(data)                                         ' データを取得し、アダプタにセットする
dt = data.Tables(0)                                        ' DataSetからDataTableを取得する 
listSubject.DataSource = dt                                ' データをDataGridViewに表示する
Con.Close()

listSubject...DataGridViewコンポーネントのname

上記のコードをまとめたもの

Imports MySql.Data.MySqlClient
Public Class DgvSubjectMaster
    Try
        Dim builder = New MySqlConnectionStringBuilder()
        ' データベース接続に必要な情報をbuilderに与える
        builder.Server = "localhost"
        builder.Port = 3306
        builder.UserID = "ユーザー名"
        builder.Password = "パスワード"
        builder.Database = "データベース名"
        Dim conStr = builder.ToString()
    
        ' データベースに接続
        Dim con As New MySqlConnection
        con.ConnectionString = conStr
        con.Open()
        
        Dim sqlStr As String = "SELECT id AS ""ID"", subject AS ""科目"" FROM subject ORDER BY id"
        Dim dt As DataTable
    
        ' データ取得のためのアダプタ設定
        Dim adapter = New MySqlDataAdapter(sqlStr, con)             
        Dim data As New DataSet
        ' データを取得し、アダプタにセットする
        adapter.Fill(data)
        ' DataSetからDataTableを取得する
        dt = data.Tables(0)
        ' データをDataGridViewに表示する
        listSubject.DataSource = dt                                
        Con.Close()
        Catch ex As Exception
            MessageBox.Show("エラーが発生しました。error:" & ex.Message)
        End Try
    End Sub

image.png

参考サイト

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?