Introduction
An article to demonstrate How to Move List Box Items to another List Box in ASP.NET and C#.
About the solution
In many web applications it is required use list boxes. Sometimes it is necessary to select some items from one list to another. In this case we use two listboxes. This article demonstrates how to perform basic operations in such case. This operations include Add/Remove/Add All / Remove All functionalities.
Background
List Box control is a standard control in Asp.net. It is similar to a dropdownlist.
Code Snippets
"TEXT-ALIGN: justify">Code to add selected item to the list
"TEXT-ALIGN: justify">Protected void btnAdd_Click(object sender, EventArgs e)
{
if (lstEmployees.SelectedIndex > -1)
{
string _value = lstEmployees.SelectedItem.Value;
string _text = lstEmployees.SelectedItem.Text;
ListItem item = new ListItem ();
item.Text = _text;
item.Value = _value;
lstSelectedEmployees.Items.Add(item);
lstEmployees.Items.Remove(item);
}
"TEXT-ALIGN: justify">}
Code to Remove selected item from the list
protected void btnRemove_Click(object sender, EventArgs e)
{
if (lstSelectedEmployees.SelectedIndex > -1)
{
string _value = lstSelectedEmployees.SelectedItem.Value;
string _text = lstSelectedEmployees.SelectedItem.Text;
ListItem item = new ListItem();
item.Text = _text;
item.Value = _value;
lstSelectedEmployees.Items.Remove(item);
lstEmployees.Items.Add(item);
}
}
Code to Remove All items from the list
protected void btnReset_Click(object sender, EventArgs e)
{
int _count=lstSelectedEmployees.Items.Count;
if (_count != 0)
{
for (int i = 0; i < _count; i++)
{
ListItem item = new ListItem();
item.Text = lstSelectedEmployees.Items[i].Text;
item.Value = lstSelectedEmployees.Items[i].Value;
lstEmployees.Items.Add(item);
}
}
lstSelectedEmployees.Items.Clear();
}
Code to Add All items to the list
protected void btnAddAll_Click(object sender, EventArgs e)
{
int _count = lstEmployees.Items.Count;
if (_count != 0)
{
for (int i = 0; i < _count; i++)
{
ListItem item = new ListItem();
item.Text = lstEmployees.Items[i].Text;
item.Value = lstEmployees.Items[i].Value;
lstSelectedEmployees.Items.Add(item);
}
}
lstEmployees.Items.Clear();
}
About Me
I am a Software Engineer handling web application projects using Visual studio 2005 .I work in bangalore.
History
Created on 23-07-2007 by George Zacharia