ASP.NET ListBox from SQL Database and Get Selected Item

  • by
asp net listbox from sql database and selected item 01

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="">
<head runat="server">
<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"
<br /><br />
<asp:Label runat="server" ID="lblItem" />
<br /><br />

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)

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

lstProducts.DataSource = cmd.ExecuteReader();
lstProducts.DataTextField = "ProName";
lstProducts.DataValueField = "Id";
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

  1. - Realtime Encode your string to Base64 format.
  2. - Realtime Decode Base64 data to plain text.
  3. - Realtime Encoding in Md5Hash.

1 thought on “ASP.NET ListBox from SQL Database and Get Selected Item”

  1. Pingback: ASP.NET ListBox Multi Select Item and Data from Database • ParallelCodes();

Comments are closed.