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

.net, vb.net, visual-studio-2008, winforms

Solution

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).

Problem

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 Step 3: Run the project Result: 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.

Original source

Related problems