CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 3 of 3

Thread: having trouble clearing a listBox that is databound.

  1. #1
    Join Date
    Dec 2009

    Unhappy having trouble clearing a listBox that is databound.

    Greetings everybody.

    I'm new to .net and WPF and I've bumped into a problem I can't seem to figure out.
    I wan't to clear all items from a listBox just prior to refresing it's data.

    Using XAML, the listBox is bound to a DataSet named movies as seen below:

    <ListBox ItemTemplate="{StaticResource listBoxTemplate}" ItemsSource="{Binding movies}" Name="listBox1" Margin="36,61,322,123" />

    Now in my C# code, if I use listBox1.Items.Clear() I get this error:

    "Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead."

    I'm not 100% sure what to make of the above error message. Someone told me to clear the bindings, in order to clear the values in the listBox, but then I can't get the values to appear in the listbox in the first place.

    Hope it made sense.

    Thx in advance.

  2. #2
    Join Date
    Sep 2002
    14 39'19.65"N / 121 1'44.34"E

    Re: having trouble clearing a listBox that is databound.

    Your ListBox is bound to a DataSet - and hence always reflects the state of the Dataset. That's why trying to manipulate the ListBox items directly leads to a conflict, and that's what the error message says. In order to clear the list, you have to modify the DataSet, and not the ListBox.

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004

    Re: having trouble clearing a listBox that is databound.

    Guido is correct. If your listbox is bound to a data model (like dataset, observablecollection, etc), then you need to do the operations on the model. With the listbox databinding any changes you make to the model (add, update, remove, clear) will be reflected in the listbox. With binding you really don't perform any operations on the listbox directly.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)