Binding Data from Database to ListBox Control in ASP.NET
In this article, we'll explore the process of binding data from a database to a ListBox control in ASP.NET. This is a common scenario where you want to populate a ListBox with data retrieved from a database, providing a dynamic and interactive user interface.
HTML Markup Language - Add ListBox
The ListBox control in ASP.NET allows for single or multiple item selection. To enable multiple item selection, set the SelectionMode property to Multiple
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
</div>
</form>
</body>
</html>
C# Coding : Namespace
Before diving into the code, ensure that you add the necessary namespaces that will help bind data from the database to the application. These include SqlConnection, SqlCommand, SqlDataAdapter, and DataSet.
using System.Data;
using System.Data.SqlClient;
C# Coding : BindCountryListBox
In the Page_Load event, we check if it is not a postback and call the BindCountryListBox method to populate the ListBox.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindCountryListBox();
}
}
private void BindCountryListBox()
{
SqlConnection conn = new SqlConnection("Data Source=.; Database=master; User ID=sa; Password=12345;");
SqlDataAdapter da = new SqlDataAdapter("select countryid, countryname from CountryTable", conn);
DataSet ds = new DataSet();
da.Fill(ds);
ListBox1.DataSource = ds;
ListBox1.DataTextField = "countryid";
ListBox1.DataValueField = "countryname";
ListBox1.DataBind();
}
The BindCountryListBox method establishes a connection to the database, retrieves data from the CountryTable, and binds it to the ListBox. The DataTextField and DataValueField properties specify which columns should be used for display and the underlying values, respectively.
Explanation of the Code
This article demonstrates the steps to bind data from a database to a ListBox in ASP.NET. The HTML markup defines the ListBox, and the C# code includes namespaces and a method to fetch and bind data from the database.
Ensure to replace the connection string and adapt the code based on your database structure. This approach offers a flexible solution for presenting dynamic data in your ASP.NET web application.
0 Comments