asp.net add listBox 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> <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.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5