Vb.net Code To Retrieve Data From Sql Server Apr 2026

Public Shared Function GetAllEmployees() As List(Of Employee) Dim employees As New List(Of Employee)() Using conn As New SqlConnection(connectionString) Dim sql As String = "SELECT EmployeeID, FirstName, LastName, Department, Salary FROM Employees ORDER BY LastName" Using cmd As New SqlCommand(sql, conn) conn.Open() Using reader As SqlDataReader = cmd.ExecuteReader() While reader.Read() employees.Add(New Employee() With .EmployeeID = reader.GetInt32(0), .FirstName = reader.GetString(1), .LastName = reader.GetString(2), .Department = reader.GetString(3), .Salary = reader.GetDecimal(4) ) End While End Using End Using End Using Return employees End Function End Class

Return employees End Function This approach loads all data into memory and works well for data binding. vb.net code to retrieve data from sql server

Return dataTable End Function

Return employees End Function

' Employee class definition Public Class Employee Public Property EmployeeID As Integer Public Property FirstName As String Public Property LastName As String Public Property Department As String Public Property Salary As Decimal Public ReadOnly Property FullName As String Get Return $"FirstName LastName" End Get End Property End Class .FirstName = reader.GetString(1)

Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ' Show loading indicator Button1.Enabled = False Label1.Text = "Loading data..." Dim employees As List(Of Employee) = Await GetEmployeesAsync() .LastName = reader.GetString(2)

Imports System.Data.SqlClient Public Async Function GetEmployeesAsync() As Task(Of List(Of Employee)) Dim employees As New List(Of Employee)() Dim connectionString As String = "Server=localhost;Database=YourDatabase;Integrated Security=True;"