简体   繁体   中英

how to Remove item from one Listbox and add into another Listbox?

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."

Don't manipulate the items via the Items property, instead add/remove items from the List that the ListBox is bound to:

<ListBox Name="lstBox1" ItemsSource="{Binding myListProperty}">
  ...etc...
</ListBox>

If your myListProperty returns a collection that implements INotifyCollectionChanged (like the ObservableCollection does) then the listboxes will automatically show the new items as they are added and the removed items will instantly disappear.

I tried by following way and its working for me.

List<object> _selecteditems = new List<object>();
foreach (var item in lstBox1.SelectedItems)
{
    _selecteditems.Add(item);
}
foreach (var item in _selecteditems)
{
  DataRow dr = dtSelctedDest.NewRow();
  dr[0] = ((DataRowView)item).Row[0].ToString();
  dr[1] = ((DataRowView)item).Row[1].ToString();
  dtSelctedItem.Rows.Add(dr);
  dtAllItem.Rows.Remove(dtAllItem.Rows.Remove.Select(string.Format("ID='{0}'", ((DataRowView)item).Row[0].ToString()))[0]);
 }
 lstBox1.DataContext = dtAllItem;
 lstBox2.DataContext = dtSelctedItem;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM