Bind ListBox, Retrieve The Multi-selected Values And Pre-select ListBox in ASP.NET WebForm

I will cover following topics for ListBox:

  1. How to bind List Box with Database?
  2. How to retrieve the Multi Selected value?
  3. How to Pre-select List Box Items from Database?

List box control allows user to select single or multiple item selection. Partially it's similar to a dropdown list.

The following are the main properties of ListBox control.

  1. Rows: By Default there is 4 rows setting , you can change according to your requirement.
  2. SelectionMode: By default SINGLE is selected, you can change to MULTIPLE.
  3. DataTextField: Field Name which display on list box.
  4. DataValueField: Field Name which ID value you going to store in saving table.
  5. Items: Hard coded value store in List Box.

Table Structure:

  1. USE [MemberCDAC]  
  2. GO  
  3. /****** Object:  Table [dbo].[tblTechnologies]    Script Date: 02/07/2016 18:03:35 ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. SET ANSI_PADDING ON  
  9. GO  
  10. CREATE TABLE [dbo].[tblTechnologies](  
  11.     [TechID] [int] IDENTITY(1,1) NOT NULL,  
  12.     [TechName] [varchar](50) NULL  
  13. ON [PRIMARY]  
  14.   
  15. GO  
  16. SET ANSI_PADDING OFF  
Table

Create a ASP.NET web site project.

ASP.NET web site project

Give Project name : ListBoxSample.

Now right click on Solution Explorer and Add new web page/form.

Right Click->ADD->ADD NEW ITEM

Add new item in project

add web form

Add the WebForm, named : SimpleListBoxBind.aspx.

In SimpleListBoxBind.aspx , we are going to bind List box from database with multi selections options.

Now double clicked on SimpleListBoxBind.aspx file.

Drag n Drop the List Box control on aspx page.

Drag n Drop the List Box control

While you click smart tag menu option.

mart tag menu option

menu

Smart Tag Menu Options:

 

  • Choose Data Source: Non-programmatically and with Wizard we can populate List Box items.
  • Edit Items: Hard coded items for List Box.
  • Enable AutoPostBack: Mark and ready List box for auto post back to server while we select any item(s).

How To Bind List Box From Database?

CODE of SimpleListBoxBind.aspx file

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="SimpleListBoxBind.aspx.cs" Inherits="SimpleListBoxBind" %>  
  2.     <!DOCTYPE html>  
  3.     <html xmlns="http://www.w3.org/1999/xhtml">  
  4.   
  5.     <head runat="server">  
  6.         <title></title>  
  7.     </head>  
  8.   
  9.     <body>  
  10.         <form id="form1" runat="server">  
  11.             <div>  
  12.                 <asp:ListBox ID="lstTech" runat="server" Height="240px" SelectionMode="Multiple" Width="190px" BackColor="#CCFFFF"></asp:ListBox>  
  13.             </div>  
  14.         </form>  
  15.     </body>  
  16.   
  17. </html>  
CODE of SimpleListBoxBind.aspx.cs file
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.Data;  
  5. using System.Data.SqlClient;  
  6. using System.Linq;  
  7. using System.Web;  
  8. using System.Web.UI;  
  9. using System.Web.UI.WebControls;  
  10. public partial class SimpleListBoxBind: System.Web.UI.Page  
  11. {  
  12.     string ConStr = ConfigurationManager.ConnectionStrings["MemberCDACConnectionString"].ConnectionString;  
  13.     protected void Page_Load(object sender, EventArgs e)  
  14.     {  
  15.         if (!IsPostBack)  
  16.         {  
  17.             BindListBox();  
  18.         }  
  19.     }  
  20.     /// <summary>   
  21.     /// To load data into ListBox control   
  22.     /// </summary>   
  23.     public void BindListBox()  
  24.     {  
  25.         SqlConnection con = new SqlConnection(ConStr);  
  26.         SqlDataAdapter da = new SqlDataAdapter("Select * From tblTechnologies", ConStr);  
  27.         DataSet ds = new DataSet();  
  28.         da.Fill(ds, "TechTable");  
  29.         lstTech.DataSource = ds;  
  30.         lstTech.DataTextField = "TechName";  
  31.         lstTech.DataValueField = "TechID";  
  32.         lstTech.DataBind();  
  33.     }  
  34. }  
Output:

see output

In above image you can see, I had selected the following Items:

 

  • ASP.NET MVC
  • C#
  • JavaScript
  • MS SQL Server

How to retrieve the Multi Selected value?

Now, we are going forward for How to Retrieve the Multi Selected Value from List Box.

Now right click on Solution Explorer and Add new web page/form.

RightClick->ADD->ADD NEW ITEM

Solution Explorer

select web page

Give file name: ListBoxSelecetedItem.aspx.

Now double clicked on SimpleListBoxBind.aspx file.

Drag n Drop the List Box control on aspx page.

List Box control

In this page following controls selected:

Control Control IDDescription
List BoxlstTech Contains all the items for selections.
Button btnSubmit Button to Submit the Selected Items.
Label lblSelectedTech Label to display selected Technologies items.

CODE of ListBoxSelectedItem.aspx file

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListBoxSelectedItem.aspx.cs" Inherits="ListBoxSelectedItem" %>  
  2.     <!DOCTYPE html>  
  3.     <html xmlns="http://www.w3.org/1999/xhtml">  
  4.   
  5.     <head id="Head1" runat="server">  
  6.         <title></title>  
  7.     </head>  
  8.   
  9.     <body>  
  10.         <form id="form1" runat="server">  
  11.             <div>  
  12.                 <asp:ListBox ID="lstTech" runat="server" Height="240px" SelectionMode="Multiple" Width="190px" BackColor="#CCFFFF"></asp:ListBox> <br /> <br />  
  13.                 <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" /> <br /> <br /> <br />  
  14.                 <asp:Label ID="lblSelectedTech" runat="server" Text="[Selected Technologies]"></asp:Label> <br />   
  15.             </div>  
  16.         </form>  
  17.     </body>  
  18.   
  19. </html>  
CODE of ListBoxSelectedItem.aspx.cs file
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.Data;  
  5. using System.Data.SqlClient;  
  6. using System.Linq;  
  7. using System.Web;  
  8. using System.Web.UI;  
  9. using System.Web.UI.WebControls;  
  10. public partial class ListBoxSelectedItem: System.Web.UI.Page  
  11. {  
  12.     string ConStr = ConfigurationManager.ConnectionStrings["MemberCDACConnectionString"].ConnectionString;  
  13.     protected void Page_Load(object sender, EventArgs e)  
  14.     {  
  15.         if (!IsPostBack)  
  16.         {  
  17.             BindListBox();  
  18.         }  
  19.     }  
  20.     /// <summary>   
  21.     /// To load data into ListBox control   
  22.     /// </summary>   
  23.     public void BindListBox()  
  24.     {  
  25.         SqlConnection con = new SqlConnection(ConStr);  
  26.         SqlDataAdapter da = new SqlDataAdapter("Select * From tblTechnologies", ConStr);  
  27.         DataSet ds = new DataSet();  
  28.         da.Fill(ds, "TechTable");  
  29.         lstTech.DataSource = ds;  
  30.         lstTech.DataTextField = "TechName";  
  31.         lstTech.DataValueField = "TechID";  
  32.         lstTech.DataBind();  
  33.     }  
  34.     protected void btnSubmit_Click(object sender, EventArgs e)  
  35.     {  
  36.         lblSelectedTech.Text = "You have Seleceted Following Technologies: ";  
  37.         foreach(ListItem item in lstTech.Items)  
  38.         {  
  39.             if (item.Selected)  
  40.             {  
  41.                 lblSelectedTech.Text += "<li><b>" + item.Text + "<b></li>";  
  42.             }  
  43.         }  
  44.     }  
  45. }  
Output:

run

How to Pre-select List Box Items from Database?

Now, we are going forward for Pre-Select List Box Items programmatically.

Now right click on Solution Explorer and Add new web page/form.

RightClick->ADD->ADD NEW ITEM.

ADD NEW ITEM

Web form

Give file name: ListBoxSelecetedItem.aspx.

Now double clicked on SimpleListBoxBind.aspx file.

Drag n Drop the List Box control on aspx page.

List Box

In this page following controls selected:

 

Control Control IDDescription
List BoxlstTech Contains all the items for selections.
Button btnSubmit Button to Submit the Selected Items.
Label lblSelectedTech Label to display selected Technologies items.

Following are our Pre selected values:

  • ASP.NET Web Form
  • C#
  • JavaScript
  • VB.NET

CODE of PreSelectListBoxItems.aspx file

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListBoxSelectedItem.aspx.cs" Inherits="ListBoxSelectedItem" %>  
  2.     <!DOCTYPE html>  
  3.     <html xmlns="http://www.w3.org/1999/xhtml">  
  4.   
  5.     <head id="Head1" runat="server">  
  6.         <title></title>  
  7.     </head>  
  8.   
  9.     <body>  
  10.         <form id="form1" runat="server">  
  11.             <div>  
  12.                 <asp:ListBox ID="lstTech" runat="server" Height="240px" SelectionMode="Multiple" Width="190px" BackColor="#CCFFFF"></asp:ListBox> <br /> <br />  
  13.                 <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" /> <br /> <br /> <br />  
  14.                 <asp:Label ID="lblSelectedTech" runat="server" Text="[Selected Technologies]"></asp:Label> <br />   
  15.             </div>  
  16.         </form>  
  17.     </body>  
  18.   
  19. </html>  
CODE of PreSelectListBoxItems.aspx.cs file
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.Data;  
  5. using System.Data.SqlClient;  
  6. using System.Linq;  
  7. using System.Web;  
  8. using System.Web.UI;  
  9. using System.Web.UI.WebControls;  
  10. public partial class PreSelectListBoxItems: System.Web.UI.Page  
  11. {  
  12.     string ConStr = ConfigurationManager.ConnectionStrings["MemberCDACConnectionString"].ConnectionString;  
  13.     protected void Page_Load(object sender, EventArgs e)  
  14.     {  
  15.         if (!IsPostBack)  
  16.         {  
  17.             BindListBox();  
  18.             PreSelectItem();  
  19.         }  
  20.     }  
  21.     /// <summary>   
  22.     /// To load data into ListBox control   
  23.     /// </summary>   
  24.     public void BindListBox()  
  25.     {  
  26.         SqlConnection con = new SqlConnection(ConStr);  
  27.         SqlDataAdapter da = new SqlDataAdapter("Select * From tblTechnologies", ConStr);  
  28.         DataSet ds = new DataSet();  
  29.         da.Fill(ds, "TechTable");  
  30.         lstTech.DataSource = ds;  
  31.         lstTech.DataTextField = "TechName";  
  32.         lstTech.DataValueField = "TechID";  
  33.         lstTech.DataBind();  
  34.     }  
  35.     protected void btnSubmit_Click(object sender, EventArgs e)  
  36.     {  
  37.         DisplaySelectedItems();  
  38.     }  
  39.     public void PreSelectItem()  
  40.     {  
  41.         //Selected Items which selected programmatically.  
  42.         List < string > _selectedTechnology = new List < string > ();  
  43.         _selectedTechnology.Add("ASP.NET Web Form");  
  44.         _selectedTechnology.Add("C#");  
  45.         _selectedTechnology.Add("JavaScript");  
  46.         _selectedTechnology.Add("VB.NET");  
  47.         if ((lstTech.Items.Count > 0) && (_selectedTechnology.Count > 0))  
  48.         {  
  49.             for (int i2 = 0; i2 < lstTech.Items.Count; i2++)  
  50.             {  
  51.                 for (int i = 0; i < _selectedTechnology.Count; i++)  
  52.                 {  
  53.                     if (lstTech.Items[i2].Text.ToString().Trim() == _selectedTechnology[i].ToString().Trim())  
  54.                     {  
  55.                         lstTech.Items[i2].Selected = true;  
  56.                     }  
  57.                 }  
  58.             }  
  59.         }  
  60.         DisplaySelectedItems();  
  61.     }  
  62.     public void DisplaySelectedItems()  
  63.     {  
  64.         lblSelectedTech.Text = "You have Seleceted Following Technologies: ";  
  65.         foreach(ListItem item in lstTech.Items)  
  66.         {  
  67.             if (item.Selected)  
  68.             {  
  69.                 lblSelectedTech.Text += "<li><b>" + item.Text + "<b></li>";  
  70.             }  
  71.         }  
  72.     }  
  73. }  
Output:

Output

Read more articles on ASP.NET:

Up Next
    Ebook Download
    View all
    Learn
    View all