Retrieving Data in VB.Net and SQL Server 2018
This is the continuation of my previous tutorial which is Saving Data in VB.Net and SQL Server 2018. This time I will teach you how to retrieve the data SQL Server database in VB.Net. In here you will be able to retrieve the data from the database and display it into the datagridview. This method is so simple and easy to follow if you are a newbie in programming. Let's begin.
Add a Button and a DataGridView in the Form and design the Form just like shown below.
Press F7 to open the code editor. In the code editor, add a method for retrieving data in the database and place it inside the datagridview.
- Private Sub loadData(sql As String, dtg As DataGridView)
- Dim da As New SqlDataAdapter
- Dim dt As New DataTable
- cmd = New SqlCommand
- With cmd
- .Connection = con
- .CommandText = sql
- End With
- da.SelectCommand = cmd
- dtg.DataSource = dt
- Catch ex As Exception
- End Try
- End Sub
Go back to the design view, double click the button to open the
click event handler of it. After that, add this code inside the “button1_clicked” event to retrieve the data in the database.
- Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
- sql = "SELECT * FROM tblperson"
- loadData(sql, DataGridView1)
- End Sub
The complete source code is included. You can download it and run it on your computer.
For any questions about this article. You can contact me @
Email – [email protected]
Mobile No. – 09305235027 – TNT
Or feel free to comment below.