65.9K
CodeProject is changing. Read more.
Home

Transfer data between two ASP.NET ListBox controls

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.50/5 (7 votes)

Feb 28, 2007

CPOL
viewsIcon

62711

downloadIcon

612

This article shows how to transfer data between two ASP.NET ListBox controls.

Screenshot - ScreenShot.jpg

Introduction

This article essentially shows how to transfer data between two ASP.NET ListBox controls. I realize this may seem rather simple, but oh well. I think the code below is pretty much self explanatory.

Default.aspx.cx
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(uxListBox1.Items.Count > 0 && uxListBox1.SelectedItem != null) {
            ListItem selectedItem = uxListBox1.SelectedItem;
            selectedItem.Selected = false;
            uxListBox2.Items.Add(selectedItem);
            uxListBox1.Items.Remove(selectedItem);
        }
    }
    protected void MoveLeft(object sender, EventArgs e) {
        while(uxListBox2.Items.Count > 0 && uxListBox2.SelectedItem != null) {
            ListItem selectedItem = uxListBox2.SelectedItem;
            selectedItem.Selected = false;
            uxListBox1.Items.Add(selectedItem);
            uxListBox2.Items.Remove(selectedItem);
        }
    }
    private void BindData() {
        uxListBox1.Items.Add(new ListItem("test1", "test1"));
        uxListBox1.Items.Add(new ListItem("test2", "test2"));
        uxListBox1.Items.Add(new ListItem("test3", "test3"));
    }
}
Default.aspx
<%@ 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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="uxListBox1" runat="server" SelectionMode="multiple" />
        <asp:Button id="uxRightBtn" runat="server" OnClick="MoveRight" Text=" > " />
        <asp:Button id="uxLeftBtn" runat="server" OnClick="MoveLeft" Text=" < " />
        <asp:ListBox ID="uxListBox2" runat="server" SelectionMode="multiple" />
    </div>
    </form>
</body>
</html>