I am trying to remove selected item from one listbox and add that into new listbox as follows code
Binding on PageLoad:
Getting the records from database into a DataTable and bind that to Listbox.
lstBox1.DataContext = dtData;
Code Bind:
List<object> _selecteditems = new List<object>();
foreach (var item in lstBox1.SelectedItems)
{
_selecteditems.Add(item);
}
foreach (var item in _selecteditems)
{
lstBox1.Items.Remove(item);
lstBox2.Items.Add(item);
}
Design:
<ListBox Name="lstBox1" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ID}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ListBox Name="lstBox2" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ID}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I am getting an error when removeing the item “Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.”
I tried by following way and its working for me.