Skip to main content

ASP.NET ListBox Multi Select Item and Data from Database

In my previous Post I explained how to fill ASP.NET Listbox from SQL Database. In this post let’s see How to create a ASP.NET Listbox which can select multiple items at once. ASP-NET ListBox Multi Select Item and Data from Database

My Database Table :

sql table

Make a new ASP.NET Web Page with name Default.aspx and Edit it as below :

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;background-color:lightblue">
<form id="form1" runat="server">
<h1>ASP.NET Multi Select ListBox from SQL Database</h1>
<asp:ListBox runat="server" ID="lstProducts" Height="250px" OnSelectedIndexChanged="lstProducts_SelectedIndexChanged"
SelectionMode="Multiple" AutoPostBack="true" />
<br />
<br />
<asp:Label runat="server" ID="lblItem" />
<br />
<br />

</form>
</body>
</html>

The web form is having a ASP.NET ListBox and its data will be filled at the page load method from the Database using provided Database Connection String. The SelectionMode property of the ListBox is set to Multiple which will enable users to select multiple items in the ASP.NET ListBox and its AutoPostBack Property is also set to true so that it can call the selectedIndexChanged Method. For Selecting Multiple Items on ASP.NET ListBox press select and start selecting items you wish.

ASP-NET ListBox Multi Select 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)
{
int y = 0;
lblItem.Text = "";
foreach (ListItem item in lstProducts.Items)
{
if (item.Selected)
{
y++;
lblItem.Text += y.ToString() + "<hr/>" + item.Text.ToString() + " Id : " + item.Value.ToString() + "<br/><br/>";
}
}
}
}

The  FillList() method will populate our ListBox from the Database table and lstProducts_SelectedIndexChanged() method will display the selected items on a ASP.NET Label to the users.