Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#WPFlistListBox
I've come across numerous articles describing how to move items from one listbox to another. I've applied suggested code to my project but all these examples negate the fact that listbox1 is databound AS WELL AS listbox2 being populated by previously stored data as in there are two bound listboxes in the UI. I've tried ObservableCollections, ArrayList's and now Lists<t>... all with the same end result. Has anyone any advice on how to do this as I get the following error when example code is applied "Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead."
 
PS. Im also trying to have listbox2 spill over into multiple columns by use of datatemplate.
 
Regards Steven
 
Code as follows:
 
cs -
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Data;
using System.Data.SQLite;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using PTWS.Class_Lib;
 
using System.ComponentModel;
using System.Windows.Data;
using System.Windows.Media;
 

namespace PTWS.MainPanelControls.FormControls.Permits
{
    /// <summary>
    /// Interaction logic for ColdWorkDraftUControl.xaml
    /// </summary>
    public partial class ColdWorkDraftUControl : UserControl
    {
        PTWDatabase db = new PTWDatabase();
        
        private ObservableCollection<CertificateLookup> CertificateLookupList = new ObservableCollection<CertificateLookup>();
 
        public ColdWorkDraftUControl()
        {
            InitializeComponent();
            
            LoadDataCertificateLookup();
// all works great untill I uncomment the next line
            //LoadDataCertificateSelected();            
        }
 
        private void LoadDataCertificateLookup()
        {
            try
            {             
                DataTable conditions;
                String query = "select lc.Section \"Section\""
                    + ", lc.Description \"Description\""
                    + ", lc.SortOrder \"SortOrder\" "
                    + "from LookupConditions lc "
                    + "where not exists (select 1 from SelectedConditions sc where sc.Code = lc.Code and sc.PermitID = 'CWP-12-00001') "
                    + "and lc.Section = 'Certificates'";
 
                    conditions = db.GetDataTable(query);
 
                foreach (DataRow r in conditions.Rows)
                {
                    CertificateLookupList.Add(new CertificateLookup()
                    {
                        Section = r["Section"].ToString(),
                        Description = r["Description"].ToString(),
                        SortOrder = r["SortOrder"].ToString()
                    });
                }
 
               listBoxCertificateLookup.ItemsSource = CertificateLookupList;
            }
            catch (Exception fail)
            {
                String error = "The following error has occurred:\n\n";
                error += fail.Message.ToString() + "\n\n";
                MessageBox.Show(error);
            }
        }
 
        void LoadDataCertificateSelected()
        {
            try
            {
                DataTable conditions;
                String query = "select Section \"Section\""
                    + ", Description \"Description\""
                    + ", SortOrder \"SortOrder\"";
                query += "from SelectedConditions where PermitID = 'CWP-12-00001' and Section = 'Certificates'";
                conditions = db.GetDataTable(query);
 
                ObservableCollection<CertificateSelected> CertificateSelectedList = new ObservableCollection<CertificateSelected>();
 
                foreach (DataRow r in conditions.Rows)
                {
                    CertificateSelectedList.Add(new CertificateSelected()
                    {
                        selectedSection = r["Section"].ToString(),
                        selectedDescription = r["Description"].ToString(),
                        selectedSortOrder = r["SortOrder"].ToString()
                    });
                }
                listBoxCertificateSelected.ItemsSource = CertificateSelectedList;
            }
            catch (Exception fail)
            { 
                String error = "The following error has occurred:\n\n";
                error += fail.Message.ToString() + "\n\n";
                MessageBox.Show(error);
            }
        }
 
        private void listBoxCertificateLookup_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                ListBoxItem myListBoxItem =
                    (ListBoxItem)(listBoxCertificateLookup.ItemContainerGenerator.ContainerFromItem(listBoxCertificateLookup.Items.CurrentItem));
                // listBoxCertificateSelected.DataContext = null;
                listBoxCertificateSelected.Items.Add(myListBoxItem);
            }
            catch (Exception fail)
            {
                String error = "The following error has occurred:\n\n";
                error += fail.Message.ToString() + "\n\n";
                MessageBox.Show(error);
            }
        }
 
        private void listBoxCertificateSelected_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                ListBoxItem myListBoxItem =
                    (ListBoxItem)(listBoxCertificateSelected.ItemContainerGenerator.ContainerFromItem(listBoxCertificateSelected.Items.CurrentItem));
 
                //listBoxCertificateLookup.DataContext = null;
                listBoxCertificateLookup.Items.Add(myListBoxItem);
            }
            catch (Exception fail)
            {
                String error = "The following error has occurred:\n\n";
                error += fail.Message.ToString() + "\n\n";
                MessageBox.Show(error);
            }
        }
    }
}
 
xaml-
<UserControl x:Class="PTWS.MainPanelControls.FormControls.Permits.ColdWorkDraftUControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    
    <Grid>
        <ListBox Name="listBoxCertificateLookup"
                 ItemsSource="{Binding}"
                 MouseDoubleClick="listBoxCertificateLookup_MouseDoubleClick"
                 IsSynchronizedWithCurrentItem="True"
                 HorizontalAlignment="Left" Width="300" Height="75" VerticalAlignment="Top" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Height="23" Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=Description}" VerticalAlignment="Top" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel IsItemsHost="True" Orientation="Vertical" />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>            
      
        <ListBox Name="listBoxCertificateSelected"
                 ItemsSource="{Binding}"
                 MouseDoubleClick="listBoxCertificateSelected_MouseDoubleClick"
                 HorizontalAlignment="Left" Width="300" Height="75" VerticalAlignment="Top" Margin="0,153,0,0">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Height="23" Orientation="Horizontal">
                    <TextBlock Name="textBlock" Text="{Binding Path=selectedDescription}" VerticalAlignment="Top" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel IsItemsHost="True" Orientation="Vertical" />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </Grid>
</UserControl>
 
class-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PTWS.Class_Lib
{
    class CertificateLookup
    {
        public string Section { get; set; }
        public string Description {get; set;}
        public string SortOrder { get; set; }
        public string selectedSection { get; set; }
        public string selectedDescription { get; set; }
        public string selectedSortOrder { get; set; }
    }
}
 
Solution
AMENDED CS File...MouseDoubleClick event code changes (make appropriate changes to LB2 accordingly)

 
CertificateLookup myListBoxItem = (CertificateLookup)((ListBox)sender).SelectedItem;
 
CertificateSelectedList.Add(new CertificateSelected()
{
selectedDescription = myListBoxItem.Description
});
 
CertificateLookupList.Remove(myListBoxItem);
Posted 16-Dec-12 2:49am
Edited 1-Jan-13 12:00pm
v5
Comments
Krunal Rohit at 16-Dec-12 8:57am
   
you want to do it without Database ?
SDavisworth at 19-Dec-12 17:30pm
   
Hi Krunal, with database. I've added my code to my question above. Thanks for your interest...
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

As per amended question...
 
Solution provided by Blachshma (http://stackoverflow.com/questions/14108531/wpf-moving-items-from-one-listbox-to-another-and-back-again-and-getting-operatio)
 
"Your problem is that you're adding items to the ListBox instead of adding and removing items to the collection the listbox is bound to.
 
Instead of doing: listBoxCertificateSelected.Items.Add(myListBoxItem);, you should be adding/removing from the CertificateSelectedList and the CertificateLookupList directly...
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

"Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead."
That sounds like a good advice.
 
Add your items to an ObservableCollection<T> myCollection; and place something like:
<ListBox ItemsSource="{Binding Path=myCollection}" />
to bind the list to the listbox. You can bind the same list to multiple listboxes.
 
You can also have a look at DataBinding in WPF[^]
 
Regards
Espen Harlinn
  Permalink  
Comments
SDavisworth at 18-Dec-12 18:33pm
   
Hi Espen I've tried implementing your suggestions, but am still pulling my hair out. I'm also thinking that I need to perhaps include some code in the USERCONTROL.RESOURCES section. Any ideas or suggested better practise would be appreciated… been working on this piece of code now for 3 weeks and slowly losing my initiative… well not really but you know what I mean. I've updated my question with my code. Please help!!!
Sergey Alexandrovich Kryukov at 29-Dec-12 21:36pm
   
A 5. —SA
Espen Harlinn at 30-Dec-12 5:22am
   
Thank you, Sergey :-D
SDavisworth at 31-Dec-12 2:35am
   
Hi Espen I've added my code... still struggling Steven
Espen Harlinn at 31-Dec-12 7:16am
   
Expose the collection as a property 'myCollection', and populate it on first access - do not set the 'ItemsSource' in your c# code, set it your xaml
SDavisworth at 1-Jan-13 0:11am
   
Thanks Espen Perhaps I should have mentioned that I'm still a novice… not sure where to change what in my attached code. I’ve looked at so many possible solutions that I’m getting lost in it all… PS. HAPPY NEW YEAR to you and family.
SDavisworth at 1-Jan-13 18:03pm
   
Hi Espen A bit sparce on direction, but I managed to apply your suggestions above with no resolve.
SDavisworth at 1-Jan-13 17:51pm
   
Hello all... I've found a solution to my problem which was ultimately caused by me trying to update the LB.Items directly instead of updating the ObservableCollection... I tried the above suggestions but did not get any resolve on the issue... I've updated my question above to include my changes for those who had a similar problem... Thanks to all

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Guruprasad.K.Basavaraju 450
1 Sergey Alexandrovich Kryukov 350
2 Shai Vashdi 318
3 OriginalGriff 265
4 Peter Leow 171
0 Sergey Alexandrovich Kryukov 9,109
1 OriginalGriff 5,290
2 Peter Leow 4,010
3 Maciej Los 3,535
4 Abhinav S 3,263


Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 1 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid