Home > DeveloperSection > Articles > Working with ListBox Control in Asp.Net

Working with ListBox Control in Asp.Net


ASP.Net ASP.Net 
Ratings:
0 Comment(s)
 5156  View(s)
Rate this:

Working with ListBox Control in Asp.Net

Use the ListBox control to create a list control that allows single or multiple item selection. Use the Rows property to specify the height of the control. To enable multiple item selection, set the SelectionMode property to ListSelectionMode.Multiple.

To specify the items that you want to appear in the ListBox control, place a ListItem element for each entry between the opening and closing tags of the ListBox control.

The ListBox control also supports data binding. To bind the control to a data source, first create a data source, such as a System.Collections.ArrayList, that contains the items to display in the control. Next, use the Control.DataBind method to bind the data source to the ListBox control. Use the DataTextField and DataValueField properties to specify which field in the data source to bind to the Text and Value properties, respectively, of each list item in the control. The ListBox control will now display the information from the data source.

If the SelectionMode property is set to ListSelectionMode.Multiple, determine the selected items in the ListBox control by iterating through the Items collection and testing the Selected property of each item in the collection. If the SelectionMode property is set to ListSelectionMode.Single, you can use the SelectedIndex property to determine the index of the selected item. The index can then be used to retrieve the item from the Items collection.

In this article for demo, I have taken a ListBox on .aspx page and populate color list in this ListBox with these background color.

.aspx code

<asp:ListBox ID="ListBox1" runat="server" Height="294px" Width="225px"></asp:ListBox>

.cs code

 

using System;

using System.Web.UI.WebControls;

using System.Drawing;

using System.ComponentModel;

 

public partial class ListBox : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            foreach (Color c in TypeDescriptor.GetConverter(typeof(Color)).GetStandardValues())

            {

                ListItem li = new ListItem();

                li.Text = TypeDescriptor.GetConverter(c).ConvertToString(c);

                ListBox1.Items.Add(li);

            }

        }

        for (int i = 0; i < ListBox1.Items.Count; i++)

        {

            ListBox1.Items[i].Attributes.Add("style", "background-color:" + ListBox1.Items[i].Text);

        }

 

    }

}

 

Output

Working with ListBox Control in Asp.Net

 

 


Don't want to miss updates? Please click the below button!

Follow MindStick