ARTICLE

Transferring data from one ListBox to another in WPF

Posted by Mahesh Chand Articles | Learn .NET July 28, 2008
This article discusses how we can transfer items from one ListBox to another in WPF.
Reader Level:
Download Files:
 

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
post comment
     

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

Posted by suneel kumar Aug 12, 2011

how can i transfer all contents at once from a listbox to another????

Posted by Saira Tanweer Mar 03, 2011

Hi,


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

THanks!

Posted by vaishnavi desai Mar 09, 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#.

Posted by Nevlyn DSousa Jan 24, 2010

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.

Posted by Manish Dwivedi Apr 08, 2009
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.