Retrieving Data in VB.Net and SQL Server 2018
Submitted by janobe on Saturday, October 12, 2019 - 10:31.
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.
Output
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.
Creating Application
Step 1
Open Saving Data in VB.Net and SQL Server 2018.Step 2
Add a Button and a DataGridView in the Form and design the Form just like shown below.Step 3
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
- Try
- con.Open()
- cmd = New SqlCommand
- With cmd
- .Connection = con
- .CommandText = sql
- End With
- da.SelectCommand = cmd
- da.Fill(dt)
- dtg.DataSource = dt
- Catch ex As Exception
- MsgBox(ex.Message)
- Finally
- con.Close()
- da.Dispose()
- End Try
- End Sub
Step 4
Go back to the design view, double click the button to open theclick 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
Add new comment
- 1548 views