views:

1180

answers:

3

Hi,

I'm using VS 2005 in a VB.Net WinForms application. I have a custom User Control that requires a variable to render its data correctly. My question is, what's the best way to require the calling sub to populate the variable? I've thought of a couple of options:

  • Have a WriteOnly property and check to see if it is "Nothing" when the User Control is loaded and throw an exception if this is the case. I don't like this because the error would be at runtime and I would like to require the variable to be populated at design time (like passing parameters to a sub/function).

  • Have a global variable to hold the variable that I want the User Control to use. I could also use the exception with this technique too, but, like the option I stated above, the error would be thrown at runtime.

What are your suggestions for populating the required variable that the User Control needs at design time?

Thanks in advance.

A: 

Add the variable as a parameter to all public constructors for the control?

Joel Coehoorn
It's often hard to do this with WinForms as the designer can get testy if you don't provide a default constructor
JaredPar
Joel, thanks for your response. It led me to the solution of passing the variable in the "Public Sub New" subroutine of the User Control and that works.
OneSource
You can have a default constructor and use attributes to make it difficult to call outside the designer.
Joel Coehoorn
+3  A: 

I've been down this road a few times with custom controls and I've come to one truth

Custom Controls must render without crashing if necessary properties are not set.

There are just far too many cases where you will get into this situation. The primary example is the WinForm designer. As soon as you drag your control onto a host, WinForms will create an instance of it and render it in the VS process. By default it will pass no variables to the constructor and hence the initial render will happen without any of your properties set.

You'll save a lot of time if you have your control render in some lesser state when the property is not set. This is how many of the standard controls work. Usually I have the control render a message to the effect of "Lacking Property X" or simply display nothing.

JaredPar
Jared, thanks for sharing your thoughts. This is good info to know for the future.
OneSource
A: 

I would overload the constructor, the default constructor would set the variable to a predetermined default value.

Anonymouse