asp.net add listBox items

asp.net add listBox items

Asp.net-ListBox-Add-Items Here is an example of how to add list items into ListBox control of Asp.net website. You need to create new instance of ListItem and add it to ListBox control. Let's see Asp.net with example of ListBox control.

<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server" Width="238px"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add To List" /><br />
        <br />
        <asp:ListBox ID="lstUsers"
             runat="server"        Height="209px" Width="141px">
         </asp:ListBox>&nbsp;<br />
    </div> 
</form>
Code behind
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class AddToList : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
string item = TextBox1.Text;
string value = TextBox1.Text;
ListItem l = new ListItem(item,value);
lstUsers.Items.Add(l);
}
}
Description

As you can see in example above, we are creating new instance of list items and adding them to list.

How to make added list items as selected items

Instance of ListItem has property called Selected, make it true or false to allow items as selected or deselected.

protected void Button1_Click(object sender, EventArgs e)
{
string item = TextBox1.Text;
string value = TextBox1.Text;
ListItem l = new ListItem(item,value);
l.Selected = true;
lstUsers.Items.Add(l);
}

Here l.Selected is set to true, After ading this item into listbox it remains selected.

Tags:

asp.net add listBox itemsListBox Asp.net Binding csharpThis page contains secure and none secure information Do you want to display the none secure itemsDo you want to display nonsecure itemsListbox select multipleAspnet Listbox Selectedindexchanged problems and solutionasp net image uploadAsp.net Interview Questions for 2 years or 3 years experianceASp.net 2.0 step by step Membership Provider C# Listbox ForeachASP.net File Handlinglistbox select event

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.