简体   繁体   中英

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

在此输入图像描述

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.

在此输入图像描述

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

The first test is from the designer and you are adding a second one in the constructor.

Either remove the test from the designer or clear the items in the constructor before adding, like this:

Items.Clear()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM