Note that there are some explanatory texts on larger screens.

plurals
  1. POUpdating ObservableCollection causes "The Parameter is incorrect" exception
    primarykey
    data
    text
    <p>I've got a weird issue I don't understand. This is in Silverlight/WP7.</p> <p>I'm filling an ObservableCollection with items, and later I want to update each of the items. </p> <p>I've managed to strip down the code to reproduce the error. My XAML is just a ListBox and a Button. </p> <pre><code> private ObservableCollection&lt;int&gt; Words = new ObservableCollection&lt;int&gt;(); public MainPage() { InitializeComponent(); listBox1.ItemsSource = Words; } private void button1_Click(object sender, RoutedEventArgs e) { List&lt;int&gt; numbers = new List&lt;int&gt;() { 1,2,3 }; foreach (var number in numbers) { var index = Words.IndexOf(number); if (index &gt; -1) Words[index] = number; else Words.Add(number); } } </code></pre> <p>The first time I run the code it fills the ObservableCollection with the numbers 1, 2 and 3, and they are displayed in the ListBox.</p> <p>The second time it is run all the code is executed, but then an unhandled exception with the message "The parameter is incorrect" is thrown.</p> <p>The weird thing is that if I remove my line in the constructor, the one where I set up the ItemsSource, the error isn't thrown. The observable collection is updated as it should.</p> <p>Also, if I comment out the "Words[index] = number" line it also works. So for some reason, when my ObservableCollection is set as the datasource to a ListBox I can't replace the item.</p> <p>Can someone explain why? (Or suggest a workaround?)</p> <p><strong>My solution;</strong> I changed my codebehind from</p> <pre><code>if (index &gt; -1) Words[index] = number; </code></pre> <p>to</p> <pre><code>if (index &gt; -1) { Words.RemoveAt(index); Words.Add(number); } </code></pre> <p>That made the problem go away.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload