Detecting if a UserConrtol is in designer or run-time

  • Thread starter Thread starter MuZZy
  • Start date Start date
M

MuZZy

Hi,

I have a user control which connects to a database in it's OnLoad event
handler. When the user control is on a form and i open this form in VS
designer, i get an exception regarding database connection. What is the
way to detect that a user control is loaded in designer vs runtime?

Thank you,
MuZZy
 
if (!this.DesignMode)
{
...
}

or, conversely,

if (this.DesignMode)
{
return;
}

which is what I most often use.

Note that the DesignMode property returns a sensible result only after
the component's window handle has been assigned. In other words, it
doesn't work in the constructor. OnLoad is a good place to test it.
 
Bruce said:
if (!this.DesignMode)
{
...
}

or, conversely,

if (this.DesignMode)
{
return;
}

which is what I most often use.

Note that the DesignMode property returns a sensible result only after
the component's window handle has been assigned. In other words, it
doesn't work in the constructor. OnLoad is a good place to test it.

Oh my... that's why it didn't work for me -i had this check in constructor.
By the way, what if i need to test it in constructor - can i somehow?

Thank you,
MuZZy
 
Not that I know of. You have to move all "run-time only" initialization
code into the Load method.
 
Bruce said:
Not that I know of. You have to move all "run-time only" initialization
code into the Load method.
The problem with that is that i might need to access some properties of
the user control after it's being created but before it's being loaded
and if i move all init code into OnLoad i will get in trouble as the
control might not be initialized when i access it
 
You don't have to move _all_ init code... just the init code that
shouldn't run at design time. Sorry, but I've never found a way around
that.
 
Bruce said:
You don't have to move _all_ init code... just the init code that
shouldn't run at design time. Sorry, but I've never found a way around
that.

Thanks for your help! With some minor tweaks i've finally fixed the control.
 
Try

protected static bool IsInDesigner {
get { return ( Assembly.GetEntryAssembly() == null ); }
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top