Boolean property returns false at runtime even though it is set to "true" via Designer

Hopefully this has a simple fix:

I created a custom textbox for my solution. To this custom control, I've added an auto property called "AllowEmpty":

Public Property AllowEmpty As Boolean

      

Both my constructors and events read this property 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 the "AllowEmpty" value to "True" in the constructor, it still stays false at runtime. Did I miss something?

Thank.

+3


source to share


1 answer


The order in which everything happens is not in your favor if you are trying to access a custom time constructor property in a component constructor.

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

  • Form1 constructor
  • Constructor constructor Form1 Form1.InitializeComponent()

  • Inside InitializeComponent, Me.components = New System.ComponentModel.Container()

  • CustomTextBox is now built
  • Come 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 constructor set properties are set here in the code after the class is created. Therefore, the constructor is not the best place to access them.

But instead you can use OnCreateControl

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

      

+4


source







All Articles