Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is New() firing twice on my inherited controls? (winforms)

Step 1: Create inhered control class

Public Class Test_Control
    Inherits ListBox

    Public Sub New()
        Items.Add("test")
    End Sub
End Class

Step 2: Drag class to form in the designer

enter image description here

Step 3: Run the project

Result:

enter image description here

Why is this happening?! I am completely stumped here.. I have googled and googled and I cannot find any solution or answer to this.

This is causing some major issues for me. I am simply trying to add an initial "Select one..." option to every newly created Combobox. Same thing happens with every inherited control class, regardless of control type (textbox/combobox/listbox/etc).

Same thing happens if I use a message box within New(). Two message boxes appear as soon as I run my application.

enter image description here

like image 256
cowsay Avatar asked Jul 25 '13 18:07

cowsay


1 Answers

You need to tell the designer to not serialize the items collection:

Public Class Test_Control
  Inherits ListBox

  Public Sub New()
    Items.Add("test")
  End Sub

  <DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
  Public Shadows ReadOnly Property Items As ListBox.ObjectCollection
    Get
      Return MyBase.Items
    End Get
  End Property
End Class

As far as the two message boxes go, MessageBoxes are just not a good debugging tool. You are probably getting the WinForms designer calling new while the runtime calling new, too (or something like that).

like image 182
LarsTech Avatar answered Oct 12 '22 11:10

LarsTech