Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » .NET 3.0/3.5 » Transferring data from one ListBox to another in WPF

Transferring data from one ListBox to another in WPF

This article discusses how we can transfer items from one ListBox to another in WPF.

Author Rank:
Technologies: Database, WPF,Visual C# .NET
Total downloads : 145
Total page views :  6428
Rating :
 5/5
This article has been rated :  1 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
TwoListBoxes.xaml.zip
 
Become a Sponsor


Related EbooksTop Videos

We have seen many requirements where a page has two ListBox controls and left ListBox displays a list of items and using a button we can add items from the left ListBox and add them to the right side ListBox and using the remove button we can remove items from the right side ListBox and add them back to the left side ListBox.

This sample shows how we can move items from one ListBox to another. The final page looks like Figure 1. The Add button adds the selected item to the right side ListBox and removes from the left side ListBox. The Remove button removes the selected item from the right side ListBox and adds back to the left side ListBox.

Figure 1

 Figure 2

The following XAML code generates two ListBox control and two Button controls.

<ListBox Margin="11,13,355,11" Name="LeftListBox" />

<ListBox Margin="0,13,21,11" Name="RightListBox" HorizontalAlignment="Right" Width="216" />

<Button Name="AddButton" Height="23" Margin="248,78,261,0" VerticalAlignment="Top"

        Click="AddButton_Click">Add &gt;&gt;</Button>

<Button Name="RemoveButton" Margin="248,121,261,117"

        Click="RemoveButton_Click">&lt;&lt; Remove</Button>

On the Window loaded event, we create and load data items to the ListBox by setting the ItemsSource property to an ArrayList.

private void Window_Loaded(object sender, RoutedEventArgs e)

{

    // Get data from somewhere and fill in my local ArrayList

    myDataList = LoadListBoxData();

    // Bind ArrayList with the ListBox

    LeftListBox.ItemsSource = myDataList;           

}

 

/// <summary>

/// Generate data. This method can bring data from a database or XML file

/// or from a Web service or generate data dynamically

/// </summary>

/// <returns></returns>

private ArrayList LoadListBoxData()

{

    ArrayList itemsList = new ArrayList();

    itemsList.Add("Coffie");

    itemsList.Add("Tea");

    itemsList.Add("Orange Juice");

    itemsList.Add("Milk");

    itemsList.Add("Mango Shake");

    itemsList.Add("Iced Tea");

    itemsList.Add("Soda");

    itemsList.Add("Water");

    return itemsList;

}

On Add button click event handler, we get the value and index of the selected item in the left side Listbox and add that to the right side ListBox and remove that item from the ArrayList, which is our data source.  The ApplyBinding method simply removes the current binding of the ListBox and rebinds with the updated ArrayList.

private void AddButton_Click(object sender, RoutedEventArgs e)

{

    // Find the right item and it's value and index

    currentItemText = LeftListBox.SelectedValue.ToString();

    currentItemIndex = LeftListBox.SelectedIndex;

   

    RightListBox.Items.Add(currentItemText);

    if (myDataList != null)

    {

        myDataList.RemoveAt(currentItemIndex);

    }

 

    // Refresh data binding

    ApplyDataBinding();

}

 

 

/// <summary>

/// Refreshes data binding

/// </summary>

private void ApplyDataBinding()

{

    LeftListBox.ItemsSource = null;

    // Bind ArrayList with the ListBox

    LeftListBox.ItemsSource = myDataList;

}

Similarly, on the Remove button click event handler, we get the selected item text and index from the right side ListBox and add that to the ArrayList and remove from the right side ListBox.

private void RemoveButton_Click(object sender, RoutedEventArgs e)

{

    // Find the right item and it's value and index

    currentItemText = RightListBox.SelectedValue.ToString();

    currentItemIndex = RightListBox.SelectedIndex;

    // Add RightListBox item to the ArrayList

    myDataList.Add(currentItemText);

 

  RightListBox.Items.RemoveAt(RightListBox.Items.IndexOf(RightListBox.SelectedItem));

 

    // Refresh data binding

    ApplyDataBinding();

}

 

Summary

 

In this article, we saw how we can transfer items from one ListBox to another by adding and remove items from the ListBoxes.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Mahesh Chand
Mahesh is a software developer with over 13 years of experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle. If you are looking for a Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
TwoListBoxes.xaml.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Bound data by Archana On February 14, 2009
Hi, Thanks for the nice article! I am actually populating my LeftListBox from a database. How can I successfully transfer the itemSource to the RightListBox? Archana :)
Reply | Email | Delete | Modify | 
Re: Bound data by Manish On April 8, 2009
Hi,
   U can do this by creating two temp datatables. When u fetch all records from the database, fill temp table1 from these records. and when u transfer the record from the leftlistbox to rightlistbox, remove that item from the temp table1 and insert into the temp table2.
Give  these two tables as datasource to the leftlistbox and rightlistbox.

Hope u got what i am trying to say.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved