How to fix "Value does not fall within the expected range" error in Silverlight - Digital Tool Factory blog

How to fix “Value does not fall within the expected range” error in Silverlight

The Problem: Your code goes about it’s merry way, adding children to parents and so forth when you get the error

Value does not fall within the expected range

The Cause: The problem is caused by two objects having the same name in the same parent. If your canvas has two StackPanels named “spOverlap” then this error is thrown. Why the error message couldn’t just say “Duplicate Name Error” no one knows. I’ve encountered this error when dynamically adding controls to the application.

The Solution (Part 1): The simple way to fix it is to simply name the newly added control with a guid or a ID number of some sort.

The Cause (Part 2): I did in fact do that, and then encountered another error, namely that things were expanding exponentially.

Here’s the situation. I have a main control (call it StronScreen), which will spawn a child control (call it StronTab), which has an event (call it StronEntityAdd) that will add a control (call it StronEntity) to StronScreen. I was adding the event to StronTab every time I spawned it, which meant that there were multiple events attached to StronTab as the user went through the application. It worked fine the first time, by which I mean that it added a single instance of StronEntity to StronScreen. The next time I spawned StronTab (this is a necessary and desirable feature of the application) and call StronEntityAdd TWO instances of StronEntity would be added to StronScreen.

The Solution (Part 2): Create the event handler as null when the page is loaded, and when StronTab is called, check to see if the event is null, and if it is, add it to StronTab. If the event handler is not null, then simply don’t add it.

A hard problem to diagnose, and the application does have to work that way, but that fixes it.


This post originally appeared on the Stronico blog – with the absorption of Stronico into Digital Tool Factory this post has been moved to the Digital Tool Factory blog


Written By Steve French


4 responses to “How to fix “Value does not fall within the expected range” error in Silverlight”

  1. Thanks STEV..
    I am new in silverlight, this is solution (first) solves my issues, now i am able to add controls (with different names…).

    Please post other solved isssues/tricks/ideas in silverlight.

    Thanks again.

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.