Step-by-step
1) I’ll continue from the previous post. You can download a project file from the previous post at here – SampleMySQL (zip format). The project was created on Microsoft Visual Studio 2005.
2) Open the Design view of Form1.
3)Drag DataGridView tool from the Toolbox window to empty area on the form.
Note: If you can’t find Toolbox window, select View -> Toolbox.
4) The DataGridView is placed on the form. The dark background indicates the area of DataGridView’s object. On Properties window, you see the default name is DataGridView1.
5) Back to the Form’s code view. Comment all the lines in Form1_Load method. These are the code from the previous post which I don’t want it to be executed.
6) Copy the code below to the form as a new method. Notice that this method is similar to retriveData() method except that it use MySqlDataAdapter rather than MySqlDataReader.
Public Sub retriveDataToDataGrid()
Try
Dim query As String = "SELECT * FROM Country"
Dim connection As New MySqlConnection(connStr)
Dim da As New MySqlDataAdapter(query, connection)
Dim ds As New DataSet()
If da.Fill(ds) Then
DataGridView1.DataSource = ds.Tables(0)
End If
connection.Close()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
Code Explanation:
Line 3-5: Create New MySqlDataAdapter object with some parameters.
Line 6: Create an empty data set.
Line 8-10: Fills a data set and set data source of DataGridView1 to a table in the data set.
Line 12: Close the connection.
retriveDataToDataGrid
7) Add code to the Form1_Load method to call retriveDataToDataGrid() when the form is loaded.
8) Run the project. You’ll see the result on DataGridView on Windows form. You may adjust the size of DataGridView to suit your screen.
The Query Result on DataGridView