Tech Blog‎ > ‎

VB.NET - Different Output in Designer VS Runtime

posted Jul 18, 2010, 2:24 PM by Victor Zakharov   [ updated Jul 26, 2010, 7:02 AM ]
The problem: let's say, you want your custom control display empty string in a certain field, if it has a default value. For example, if your Text field on a custom Label control is identical to its name, show Text field as blank. Would be nice if it worked both ways, i.e. leaving Text field blank would make it identical to the name (or following a certain pattern).

I went through different websites and forums looking for solution, with different opinions ranging from 'not possible' to 'need some special property attributes'. Well, not possible was not an acceptable solution and properties did not work for me, so I started my research. Just as I was hoping, you might first think this is a pre-processor directive, similar to #IF / #ENDIF. Surprise here! It is actually a runtime check.

A boolean variable DesignMode is available at class level. Usage is pretty straightforward:

If Me.DesignMode Then ...

With this approach, you can create interesting behaviors. Make sure you remember what the defaults are and how they are changing throughout code execution. Otherwise you are looking to spend more debugging hours with it. Just as I did once. :)

UPD: I thought an example would be nice at this point, so here's how you can implement your property to get the above behavior:

Public Class MyButton : Inherits Button

  Dim _myProperty As String

  Public Property MyProperty As String
      If Me.DesignMode AndAlso _myProperty = Me.Name Then Return String.Empty  'LINE 1, see logic below
      If _myProperty = String.Empty Then _myProperty = Me.Name  'LINE 2
      Return _myProperty
    End Get
    Set(ByVal Value As String)
      _myProperty = Value
    End Set
  End Property

End Class

LINE 1. If your property equals to name, display blank value in designer.
LINE 2. If you force your property blank, make it equal to the name (it will still look like it's blank in designer, because of the previous line).