Adding Constructors to WinForms in .NET 2.0

Properties aren't always necessary for WinForms. Sometimes, I like to create alternate constructors and pass the information in through a parameter to a private member.

In VS2003, this worked without incident. My forms were always displayed just fine. However, in VS2005, when I displayed the form, it was the default size, and didn't have any controls. I spent about 30 minutes trying to track down why I was getting NullReferenceExceptions trying to bind to to a DataGridView, and the form was blank. I finally had to crack open Reflector and see that the compiler wasn't as nice to me as it used to be.

I filed this as a bug in the MSDN Product Feedback Center, so if you can reproduce it, please vote on it.

4 Comments

  • In VS 2005 with C#, I haven't had any problems with parameters in form constructors. Did you make sure that you either chain your constructor so that the default constructor is called too (I'm not sure the syntax in VB.Net, but it'd be MyConstructor(string foo) : this() in C#) or call InitializeComponent from your additional constructor. There's really no magic going on... the default constructor just calles that method, so any other constructors need to as well, either explicitly or by calling the other constructor.



    --Oren



  • Are you saying that C# (or VB) no longer implicitly calls the parameterless constructor when writing other constructors?



    Either way, I don't think this is a designer issue. InitializeComponent is never called in the designer unless you're dealing with inherited forms.

  • Tim, yes that's what I'm saying. But it's not a designer issue. I'm saying at <b>runtime</b>, if you call a different constructor without explicitly creating a parameterless constructor, InitializeComponent is never implicitly called.

  • Although I detest what the VB team has done with the default ctor being optional, I still don't see your issue, maybe you can explain further.



    If you add a non-parameterless ctor to a form, you have to explicitly call either InitializeComponent or the default parameterless constructor (which itself calls InitializeComponent).



    I don't see that statement being false in either VS.NET 2003 or VS2005. What am I missing?



    <em>As an aside, it might help the VB team if you told them which startup model you chose now that they have introduced yet another one (have I said how much I hate where they are taking the language).</em>

Comments have been disabled for this content.