Friday, December 26, 2008

How to shift the Listbox selected item, Left to Right and Right to Left?

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Listbox Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="LeftListBox" runat="server" SelectionMode="multiple" />
<asp:Button ID="RightBtn" runat="server" OnClick="MoveRight" Font-Bold="true" Text=" > " />
<asp:Button ID="LeftBtn" runat="server" OnClick="MoveLeft" Font-Bold="true" Text=" < " />
<asp:ListBox ID="RightListBox" runat="server" SelectionMode="multiple" />
</div>
</form>
</body>
</html>

========Code Behind========
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}

protected void MoveRight(object sender, EventArgs e)
{
while (LeftListBox.Items.Count > 0 && LeftListBox.SelectedItem != null)
{
ListItem selectedItem = LeftListBox.SelectedItem;
selectedItem.Selected = false;
RightListBox.Items.Add(selectedItem);
LeftListBox.Items.Remove(selectedItem);
}
}

protected void MoveLeft(object sender, EventArgs e)
{
while(RightListBox.Items.Count > 0 && RightListBox.SelectedItem != null)
{
ListItem selectedItem = RightListBox.SelectedItem;
selectedItem.Selected = false;
LeftListBox.Items.Add(selectedItem);
RightListBox.Items.Remove(selectedItem);
}
}
private void BindData()
{
LeftListBox.Items.Add(new ListItem("Kanna", "Kanna"));
LeftListBox.Items.Add(new ListItem("Ram", "Ram"));
LeftListBox.Items.Add(new ListItem("Gokul", "Gokul"));
}
}

1 comment:

gaamana said...

Hi kannabiran,
Your blog is very good in content and value but please align the code properly and change the background color.

regards
gaamana

 
Feedback Form