May 23, 2011

Move Items from one ListBox to another ListBox in asp.net web application

Movement of items from one ListBox to another ListBox in asp.net is a typical issue sometimes programmers face. However in windows application it seems to be a common practice. It is due to the postback nature of asp.net web page. But we can do it. In my case I had to explore the situation in one of my projects where I had to convert a windows based project into web based one. Anyway I have presented below the way I use to code to move items from one asp.net ListBox control to another asp.net ListBox control.

Fig: Moving items from one asp.net ListBox control to another asp.net ListBox control

The left side ListBox in the above figure is listBoxFrom and another is listBoxTo. The top textbox is txtAddItem and top button is btnAddItem. The textbox and the button are used to add new items into the left ListBox. The remove button is used to remove the selected item from the ListBox .

Add Item in Source ListBox

public void AddItemInSourceListBox()
{
//do not let add empty into the source listbox
if (txtAddItem.Text == "")
{
return;
}

ListItem item = new ListItem();
item.Value = txtAddItem.Text;
item.Text = txtAddItem.Text;

listBoxFrom.Items.Add(item);
}

We have two buttons to move items left and right as indicated by the arrows in the button text. The left button is btnAdd and the right button is btnRemove. We should handle the button click event handler to move items from one ListBox to another.

//when btnAdd i.e. the button with double left arrow is clicked
//this moves item from source ListBox to destination ListBox
protected void btnAdd_Click(object sender, EventArgs e)
{
if (listBoxFrom.SelectedIndex == -1)
{
return;
}

ListItem item = new ListItem();
item.Value = listBoxFrom.SelectedItem.Value;
item.Text = listBoxFrom.SelectedItem.Text;

listBoxTo.Items.Add(item);
listBoxFrom.Items.Remove(item);

}

//when btnRemove i.e. the button with double right arrow is clicked
//this moves item from destination ListBox to source ListBox


protected void btnRemove_Click(object sender, EventArgs e)
{
if (listBoxTo.SelectedIndex == -1)
{
return;
}

ListItem item = new ListItem();
item.Value = listBoxTo.SelectedItem.Value;
item.Text = listBoxTo.SelectedItem.Text;

listBoxFrom.Items.Add(item);
listBoxTo.Items.Remove(item);
}

Happy Programming!

No comments:

Post a Comment