Lab 4 - Display Customer Names from SQL Server
Problem Statement
Write a web application that fetches customer names from a SQL Server database and displays them on the webpage.
Code Implementation (VB.NET)
ASP.NET Code (CustomerPage.aspx.vb)
Imports System
Imports System.Data.SqlClient
Partial Class CustomerPage
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadCustomerNames()
End If
End Sub
Private Sub LoadCustomerNames()
Dim connectionString As String = "Server=COMPUTER\\SQLEXPRESS;Database=PVFC;Integrated Security=True;"
Dim query As String = "SELECT Customer_Name FROM Customer_t"
Using conn As New SqlConnection(connectionString)
Using cmd As New SqlCommand(query, conn)
Try
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
Dim customerNames As New List(Of String)()
' Read all customer names
While reader.Read()
customerNames.Add(reader("Customer_Name").ToString())
End While
' Display all customer names
If customerNames.Count > 0 Then
lblCustomerNames.Text = String.Join("<br/>", customerNames)
Else
lblCustomerNames.Text = "No customer data found."
End If
Catch ex As Exception
lblCustomerNames.Text = "Error: " & ex.Message
End Try
End Using
End Using
End Sub
End Class
Sample Outputs
Customer names will be displayed like below after the application fetches data from the database:
Demonstration
Click the button below to view the customer names loaded from the SQL database:
View Demo Table