Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » Learn .NET » 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 :
Page Views : 17704
Downloads : 404
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
TwoListBoxes.xaml.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry 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 Sharepoint, 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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
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 | 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 | Modify 
adding selected item from listbox1 to listbox2 and simultaneously deleting the selected item in listbox1 by Nevlyn On January 24, 2010
Hi...I have 2 listboxes-listbox1 and listbox2.
listbox1 has got some items and listbox2 is empty.
On selecting(clicking) an item from listbox1 to i want it to move to listbox2 and simultaneously delete the selected item in listbox1.
I do not have any other controls on the form.
I am trying this code
 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string str;
            str = listBox1.SelectedItem.ToString();
            listBox1.Items.Remove(listBox1.SelectedItem);
            listBox2.Items.Add(str);  
        }
however I am getting an exception on selecting an item.
This code works with only 1 operation at a time.i.e.I have to comment the 2nd operation.
Can you kindly modify this code and see if it works.
Kindly help me.I am new to C#.
Reply | Email | Modify 
Copy multiple selected listbox items from one listbox to another listbox by vaishnavi On March 9, 2010
Hi,

Nice article.
How do i copy/move mutiple selected items from one listbox to another?

THanks!
Reply | Email | Modify 
Hii by Saira On March 3, 2011
how can i transfer all contents at once from a listbox to another????
Reply | Email | Modify 
Getting NullReferenceException was unhandled by suneel On August 12, 2011
Hello, Thanks for the code. I was trying to run the code and i am getting the error at line currentItemText = LeftListBox.SelectedValue.ToString(); error: System.NullReferenceException was unhandled Message=Object reference not set to an instance of an object. Source=WpfApplication5 StackTrace: at WPFControlsSample.TwoListBoxes.AddButton_Click(Object sender, RoutedEventArgs e) in c:\users\suneelkumar.p\documents\visual studio 2010\Projects\WpfApplication5\WpfApplication5\TwoListBoxes.xaml.cs:line 61 at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e) at System.Windows.Controls.Primitives.ButtonBase.OnClick() at System.Windows.Controls.Button.OnClick() at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e) at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e) at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget) at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent) at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e) at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget) at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args) at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted) at System.Windows.Input.InputManager.ProcessStagingArea() at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input) at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport) at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel) at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.Run() at System.Windows.Application.RunDispatcher(Object ignore) at System.Windows.Application.RunInternal(Window window) at System.Windows.Application.Run(Window window) at System.Windows.Application.Run() at WpfApplication5.App.Main() in c:\users\suneelkumar.p\documents\visual studio 2010\Projects\WpfApplication5\WpfApplication5\obj\x86\Debug\App.g.cs:line 0 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: Please help me to fix it
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.