Adding a user control "The Enumerator is not valid" - wpf

I'm using Visual Studio 2010 to create a small WPF application. I've created a user control that I am now trying to add to my main form. The user control does show up in toolbox but every time I try to drag the control to the form I get the error:
The enumerator is not valid because the collection changed.
I should know what's wrong and it is bugging me that I can't figure it out.

You have a bug in the constructor of the usercontrol - you are using a foreach-loop over an IEnumerable and while the loop is running, the IEnumerable is changed, this is not allowed with a foreach loop. Use a for loop instead if you are manipulating the Collection you are iterating over.

The problem here is that you don't know what code is throwing the exception.
WPF is terrible about exceptions, especially in constructors. The framework insists on catching and re-throwing a new exception, usually multiple times, and it's difficult to find the original stack trace. I've found the easiest way to track down this kind of error is to tell Visual Studio to stop as soon as the exception is thrown, rather than waiting until WPF has re-thrown it a couple of times and made the details difficult to dig out.
I don't have Visual Studio 2010 in front of me, but here's how to do this in VS2008 -- 2010 is probably similar:
Go to the Debug menu > Exceptions...
Next to "Common Runtime Language Exceptions", check the box in the "Thrown" column
Then debug your app again. It will stop at the line that's actually causing the problem, and it'll be much easier for you to see what's going on. And if you're still not sure why it's throwing an exception, you'll be able to post a code sample.

In order for a user control to function properly you need to have a constructor that takes zero arguments. This way the form designer has a way to render the control in a "default" manner.
I then overloaded my constructor to take the arguments I needed to actually run the control properly and everything worked as expected.

You need to:
Remove the DLL reference
Add a reference to your control
Rebuild the solution
Add your control. It should work!

Related

VS2010 Winform designer alterate decent code

I'm encountering a problem with the WinForm designer. I made a new UserControl, I added a DataGridView, some other elements and a TreeView. With the gui I named all those new components. Now it's time to code that stuff and I realise that the designer missnamed my node of my TreeView. The Designer also added new columns from my DataSource even if it was set to AutoGenerateColumn to false. I though: "Well time to clean some Designer crap again..." and I cleaned that stuff up in the InitializeComponent function (I know it's labeled "Do not modify with the code editor" but... do I have the choise?
Anyway, my problem is : When I go back on the Design view, the VS Designer seems to regenerate the code back but not even how it was. Now the designer declares my DataGridView and my TreeView as local members of InitializeComponent function. I can easily repair and undo my changes but I would like to understand and know if there is a way to disable the auto code generation of the designer.
Also, I tried to make another function which have all what I need so the designer don't screw it up and call it into the initialize component. This solution works at run time but not on Design view. I'm kinda low.
As far as I know, the short answer is no. If something is marked as Do not edit due to code generation., then do not edit it :). I would suggest reading up on partial classes, as that is how you can modify classes without actually messing with the auto generated code. In your case, you will need to go into the designer and fix everything there so that the auto generation works as you expect it to.

Trouble finding source of a designer exception in VS2010

When loading the mainform of a WinForms app I'm working on, I encountered a familiar exception: a "To prevent possible data loss before loading the designer, the following errors must be resolved" error. The stacktrace is as follows:
Object reference not set to an instance of an object.
Instances of this error (4)
1. Hide Call Stack
at System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object component, Object value)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkPropertyDescriptor.SetValue(Object component, Object value)
at System.Windows.Forms.Design.ControlDesigner.CanResetSizePropertyDescriptor.SetValue(Object component, Object value)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializePropertyAssignStatement(IDesignerSerializationManager manager, CodeAssignStatement statement, CodePropertyReferenceExpression propertyReferenceEx, Boolean reportError)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeAssignStatement(IDesignerSerializationManager manager, CodeAssignStatement statement)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)
I know what's causing this error -- there are four lines buried somewhere in the MainForm that make reference to an image object that doesn't exist at design time. I even have an idea of how to fix the error, thanks to this post at MSDN. The trouble is, I can't find the lines from which the exception is thrown. Normally I would navigate to the exception using the Error List window, but it says that there are zero errors. Any ideas as to how I can locate the offending lines?
I usually find that this relates to a user control hosted on the form that relies on a DI container or similar, but as you say it is sometimes difficult to determine the source from the call stack the designer provides. If you're hosting a lot of controls, to figure out which controls are causing the issue without diving into each one you could:
Make a list of the user controls that are directly hosted on the form, then
Create a new temporary form, then
Drop each user control in your list onto the form to see which one kills the designer

System.ExecutionEngineException PropertyChanged

If anyone can provide some help for this one, I'd be very grateful!
We are using: Silverlight 3 / MVVM / Blacklight DragDock Control / ComponentOne Silverlight Controls
I have a Silverlight application that relies heavily on the MVVM pattern. The application has seemingly been running fine, until recently. I have started to notice semi-random (semi-random = over a long enough period of time ~2 - 5 mins) I can reproduce a System.ExecutionEngineException coming from the PropertyChanged event being raised. The property name which the notification is being raised for is not always the same property name (the firing of the property change event happens in a base ViewModel class).
The code basically looks like this:
if (PropertyChanged != null) Application.Current.RootVisual.Dispatcher.BeginInvoke( () => PropertyChanged(this, new PropertyChangedEventArgs(propertyName)));
The code works for everything else in the application. Basically everything that throws off a property changed event goes through this. I'm not sure why this is failing all of a sudden. Please throw some thoughts my way.
I've been knee deep in windbg trying to get some grasp on what is going on, and still have very little. I'd by happy provide a dump or any other information that might be helpful. Obviously, there is very little information given from this particular error...
Thank you ahead of time, David Justice
A question you might ask yourself: is this ExecutionEngineException happening in IE only and, for instance, not in FireFox?
I know Silverlight is supposed to be browser-independent, but I already encountered a similar known Silverlight-issue that occured randomly in IE only.
The fact that you get an ExecutionEngineException is pointing out that the SL runtime blows up for some reason.
This exception is quite the exotic one. If one gets thrown, it's Game Over, 0 Continues for the CLR. No managed code can catch that exception.
When I ran into it, it was the result of a driver writing into a buffer that wasn't marshaled properly and so was not pinned, and the CLR moved the buffer while the driver was writing into it. It wouldn't crash instantly, but usually happened after the mouse ran over the form's menu bar (which probably resulted in creating and destroying lots of small objects, which then lead to the CLR running the GC and compacting the managed heap). Even though one of my worker threads was communicating with the driver, it was the main thread that threw the exception, which made things way more confusing.
Make sure things are being marshaled properly. If ANYTHING is being passed back and forth to unmanaged code, make sure you use GCHandle to pin the objects.

Is it OK to change a winforms designer file?

I have created a class that is simply THIS
Class UserControlBase
Inherits UserControl
End Class
Then I changed the Inherits clause in each of my UserControls designer file to
Inherits UserControlBase
I know that generally you shouldn't manually mod the designer file. But in cases like this what else can you do? Is this OK? Is there a best practice I don't know about? Is there some other way to accomplish the same end (extending UserControl) ?
I have not had issue changing the Inherits line, adding Namespacing, or adding Imports/Using statements. If you need to do any of these 3, you won't find many other ways to handle these requirements.
I change them all the time in my C# projects... often it's the easiest way to duplicate something that you've done once in the designer to a similar form and you want to do the same thing in a different form. Visual Studio is perfectly capable of reading in your changes and incorporating it into the designer. I really don't know why there is a comment saying not to edit it. My advice would be just make sure you use source control, go ahead and edit it, test it well, and if it works, great, if not you can always back out your edits.
No. It's never a good idea to modify a file that's generated.
The Designer files are pretty simple code; the only thing that you'll typically find in there to complicate matters (but only slightly) is BeginInit/EndInit calls at the top and bottom of the file--between those the code is pretty forgiving.
*That said, do not put any code in there that will only execute at Runtime. Any runtime-dependant code will fail at design-time, so trying to open your control in Design view will blow chunks. It used to give you the Red Screen of Darn, but I'm not sure what effect the IDE has notwadays--but if things blow up and the usual tricks fail to remedy them then try removing your customized sections.
Further on that note (not to scare you, but rather to hopefully head off some of the difficulties we had) the means of determining if your code is executing in Runtime or Designtime often fail if your code is not part of the currently built solution/project.
So to bring it all home, simple UI layout/winforms modifications are perfectly fine to do by hand in the designer code. Databinding and external dependencies (with the exception of calling third party control libraries) should be cautiously approached.

Custom Control and Visual Studio 2008 SP1

I've created a custom control (a class that inherits from Control). When I put it on a Form I can work with it on Visual Studio IDE. It shows me an error and I don't see the form.
The error message is this: La variable 'ctrlImagen' no está declarada o no se asignó nunca.
It's a winform for a Compact Framework app.
How can I solve this? (it the class inherits from UserControl it works perfectly)
Sounds crazy, but Visual Studio is selectively executing code for your control in the designer. First thing to check is your constructors. Make sure you have an empty, default constructor, that is public, even if you never plan on using it. After that make sure any code you have tied to layout events (such as resize) are good to go, these are likely the culprits, as thats where I always find problems when my custom controls don't work in the designer.
It sounds like you have a bug in the code for your Control. This sounds like a runtime error that is preventing the control from rendering.
Re-read your code and look for potential null-pointer exceptions, unassigned variables, stack overflows, etc. The bug is lying in their somewhere.
Any chance your user control doesn't have a public default constructor? I can get a similar error "The variable 'userControlX' is either undeclared or was never assigned' if the constructor isn't public.
Would need more info, though.
It seems a design time exception has happened in initialization logic that gets executed before your form initialization logic executed. A good example would be a NullPointerException fired by the default constructor (or one or more methods it invokes) of a user control that contained by your form.
I put this on constructor to solve the problem:
this.ClientSize = new Size(21, 21);
The beging of my class is this:
public class ControlMapa : Control
{
public ControlMapa()
{
this.ClientSize = new Size(21, 21);
...
Thank you!

Resources