Friday, June 29, 2012

move items from one listbox to another listbox in asp.net

Now i will show how to add the items to one list box to another list box.In this example i have taken two list boxs with two button.if i click on the MoveRight button the left list box item is passed to right side list box.The reverse process has done for Moveleft button.In this code i removed the item which will be passed to another list box
Aspx:
<form runat="server" id="test">
<h2>
List Box Example
</h2>
<table><tr><td><asp:ListBox ID="listLeft" runat="server">
<asp:ListItem>Bhaskar</asp:ListItem>
<asp:ListItem>Siva</asp:ListItem>
<asp:ListItem>Venky</asp:ListItem>
<asp:ListItem>Ram</asp:ListItem>
<asp:ListItem>Balu</asp:ListItem>
<asp:ListItem>Krishna</asp:ListItem></asp:ListBox></td>
<td>
<asp:Button ID="MoveRight" runat="server" Text=">>" onclick="MoveRight_Click1" /><br />
<asp:Button ID="MoveLeft" runat="server" Text="<<" onclick="MoveLeft_Click1" /></td>
<td> <asp:ListBox ID="listRight" runat="server"></asp:ListBox></td></tr></table>
</form>
CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void MoveRight_Click1(object sender, EventArgs e)
{
if (listLeft.SelectedItem != null)
{
ListItem li = listLeft.SelectedItem;
listLeft.Items.Remove(li);
li.Selected = false;
listRight.Items.Add(li);
}
}
protected void MoveLeft_Click1(object sender, EventArgs e)
{
if (listRight.SelectedItem != null)
{
ListItem li = listRight.SelectedItem;
listRight.Items.Remove(li);
li.Selected = false;
listLeft.Items.Add(li);
}
}
}

No comments:

Bel