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.

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. figure 1

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.
  1.        
  2.     Private Sub loadData(sql As String, dtg As DataGridView)
  3.         Dim da As New SqlDataAdapter
  4.         Dim dt As New DataTable
  5.  
  6.         Try
  7.             con.Open()
  8.  
  9.  
  10.             cmd = New SqlCommand
  11.  
  12.             With cmd
  13.                 .Connection = con
  14.                 .CommandText = sql
  15.             End With
  16.             da.SelectCommand = cmd
  17.             da.Fill(dt)
  18.  
  19.             dtg.DataSource = dt
  20.         Catch ex As Exception
  21.             MsgBox(ex.Message)
  22.         Finally
  23.             con.Close()
  24.             da.Dispose()
  25.         End Try
  26.     End Sub

Step 4

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.
  1.    
  2.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
  3.         sql = "SELECT * FROM tblperson"
  4.         loadData(sql, DataGridView1)
  5.     End Sub  
Output figure 2 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.

Add new comment