I have a funky problem that has a workaround, but I want to keep code as similar as possible. The issue centers on a particular variable in the base class for my user controls that may or may not be null, and it should never be null.
Basically I have a number of user controls with a single base class which grabs an instance of my main form window so the user control has access to main form properties and can call methods on the main form. Here is a snippet (this.frmParent is a public member):
private void ucBase_Load( object sender, EventArgs e )
{
// Establish the link to the main form.
this.frmParent = FindForm() as frmMain;
}
Then each user control shares this base class:
public partial class ucLiberty : ucBase
Then in the main form, I'll call the user control like this:
ucLiberty Liberty = new ucLiberty();
IQDevicePath = Liberty.GetIQDrivePath();
For some reason, when I instantiate the user control (in this case it's in the main form), the frmParent variable in the base class may or may not be populated with a non null value.
I noticed that the load event in the user control was not firing. I found a method called CreateControl() which is supposed to force the creation of the control, and then my load event started fireing, however when I traced execution in the debugger and I got to the base class where it was trying to populate frmParent, FindForm() would not always return a non null value.
I have other user controls where I don't have this issue with, and the difference between them is that some user controls have child controls and some do not have child controls. The one's without child controls have this problem.
My workaround is to monitor which user control FindForm() fails in, and in that user control's load event, assign the value with a call to the main form's constructor, something like this:
this.frmParent = new frmMain();
However, I still have to have the call to CreateControl() for the load event to fire, and I don't like the idea of requiring future maintainers to have to have explicit knowledge of different behavioral imperatives. In other words, I'd like my user controls to all work the same way to keep maintenance simple.
I have torn my code apart and cannot figure out why sometimes the user control's load event may or may not fire, and why the call to FindForm() in the user control base class fails.
Does anyone have any ideas about how to solve these issues? Thanks.