Skip to main content
asp net listbox from sql database and selected item 01

ASP.NET ListBox from SQL Database and Get Selected Item

Let’s see how to Populate or Fill ASP.NET ListBox from MS SQL Database and How to get ASP.NET Listbox Selected Item.asp net listbox from sql database and selected item.

Database Table :

sql table

Create a new ASP.NET Web Form with name Default.aspx and edit it as below (You can use your existing ASP.NET form too) :

Default.aspx :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="font-family:Calibri;">
<form id="form1" runat="server">
<h1>ASP.NET ListBox from MS SQL Database.</h1>
<asp:listbox runat="server" ID="lstProducts" Height="250px" OnSelectedIndexChanged="lstProducts_SelectedIndexChanged"
AutoPostBack="true"/>
<br /><br />
<asp:Label runat="server" ID="lblItem" />
<br /><br />
</form>
</body>
</html>

The Web page will have a ASP.NET ListBox which will be filled or populated on the Page load method and ASP.NET Label to show the selected item on the ListBox. The ListBox has the onSelectedIndexChanged method which will help in providing the selected item in the ListBox. Also the AutoPostBack property for the ListBox is set to true.

asp net listbox from sql database and selected item 01

And Edit the code file as below :

Default.aspx.cs :

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillList();
}
}

public void FillList()
{
try
{
SqlConnection con = new SqlConnection(@"Data Source=vibes\sqlexpress;Initial Catalog=ParallelCodes;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("Select distinct Id,ProName from Producttbl", con);

lstProducts.DataSource = cmd.ExecuteReader();
lstProducts.DataTextField = "ProName";
lstProducts.DataValueField = "Id";
lstProducts.DataBind();
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{

}
}
protected void lstProducts_SelectedIndexChanged(object sender, EventArgs e)
{
lblItem.Text = "Selected Item : " + lstProducts.SelectedItem.Text.ToString()
+ "<br/>Selected Value : " + lstProducts.SelectedValue +
"<br/>Selected Index : " + lstProducts.SelectedIndex.ToString();
}
}

The FillList() method will fill or Populate our ASP.NET ListBox from the Database with provided Database connection string and SQL Query.

TheĀ lstProducts_SelectedIndexChanged() method will display the Selected Item and Selected Value in the ListBox and show it on a ASP.NET Label.

asp net listbox from sql database and selected item 01



One thought to “ASP.NET ListBox from SQL Database and Get Selected Item”

Comments are closed.