Creativity, Innovation... Failure



Detecting design mode

Lets say you've just created a user control or customized an existing control from the .Net Framework and you want the bahavior to be different when you're in design mode vs execution mode. How can you do it?

Solution #1: DesignMode Property 

The first an very intuitive approach is to use the DesignMode property of your control. The problem is that it will always return false if it has a parent... not so great

Solution #2: Design Mode Property with a twist 

The solution then is to go up the control hierarchy and find the parent with the right value!
The resulting code will look a little like this:

public bool IsDesignMode ()
{
    Control instance = this;
    while (instance != null)
    {
        if (instance.Site == null) return false;
        if (instance.Site.DesignMode) return true;
        instance = instance.Parent;
    }
    return false;
}

Using this method can prevent errors where the GUI does not draw properly in design mode because it tries to access data (i.e. database connection)
The biggest limitation is that you can't call the method from the constructor because the parent may not be set yet!

Of course there are other solutions but they are not as elegant. Here's one of them:

bool designMode = Application.CompanyName == "Microsoft Corporation";

This solution works from the constructor, so it does have its advantages...

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

July 9. 2008 20:42

pix98

The line of code...
bool designMode = Application.CompanyName == "Microsoft Corporation";
How does it work? It it a third solution or a workaround to the redraw problem?

pix98

July 10. 2008 01:36

marivet

bool designMode = Application.CompanyName == "Microsoft Corporation";

This is a third solution to know if you are in design mode. Since the second one doesn't work in the constructor, I mention this one so you can check if you are in design mode from the constructor if necessary (No limitations.. but it's just plain ugly!!)

marivet

November 13. 2008 10:37

Morten Grøtan

Thanks a bunch! You saved my day. I've been poking around, trying to use various sorts of FindControl attempts to locate the "ancestor" control (top-most parent besides the hosting form itself), but to no avail.
The other "solutions" have all been tied to specific types of controls or specific IDs.

Your solution is generic and straight-forward, and most importantly: It works!

Morten Grøtan

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

July 3. 2009 21:39