Renato
Renato

Reputation: 556

Boolean property returns false at runtime despite being set to "true" via Designer

Hopefully this has a simple fix:

I have created a custom textbox for my solution. To that custom control I added an auto property called "AllowEmpty":

Public Property AllowEmpty As Boolean

Both my constructor and event read that property's value and act accordingly:

Public Sub New()

    If AllowEmpty Then
        Text = String.Empty
    Else
        Text = "0"
    End If

End Sub

Private Sub CustomTextBox_TextChanged(sender As Object, e As EventArgs) Handles Me.TextChanged

    If AllowEmpty Then
        Text = String.Empty
    Else
        Text = "0"
    End If

End Sub

However by setting a breakpoint I see that if I set "AllowEmpty" to True on the Designer, it's still false at runtime. Am I missing something?

Thanks.

Upvotes: 3

Views: 812

Answers (1)

djv
djv

Reputation: 15774

The order that things happen is not in your favor, if trying to access a design-time set custom property in the component's constructor.

Assuming this CustomTextBox is on Form1, here is what happens:

  1. Form1 constructor
  2. Form1 constructor calls Form1.InitializeComponent()
  3. Inside InitializeComponent, Me.components = New System.ComponentModel.Container()
  4. CustomTextBox is constructed now
  5. Back to Form1.InitializeComponent()

Then this code in InitializeComponent()

'CustomTextBox1
'
Me.CustomTextBox1.AllowEmpty = True ' <--- that is the designer set value
Me.CustomTextBox1.Location = New System.Drawing.Point(12, 12)
Me.CustomTextBox1.Name = "CustomTextBox1"
Me.CustomTextBox1.Size = New System.Drawing.Size(100, 20)
Me.CustomTextBox1.TabIndex = 0
' ...

As you can see, any designer set properties are set in code here, after the class is constructed. So the constructor is not the best place to access them.

But you can instead use OnCreateControl

Protected Overrides Sub OnCreateControl()
    MyBase.OnCreateControl()
    If AllowEmpty Then
        Text = String.Empty
    Else
        Text = "0"
    End If
End Sub

Upvotes: 4

Related Questions