简体   繁体   English

如何将项目添加到用户控件内的列表框?

[英]How do I add items to a listbox inside a user control?

I have a user control (XListBox) with a listbox (ListBox1) and a button on it.我有一个用户控件(XListBox),上面有一个列表框(ListBox1)和一个按钮。 The user control is on a form (Form1) which also has a button on it.用户控件位于一个窗体 (Form1) 上,该窗体上也有一个按钮。 The code is shown below.代码如下所示。 If click the button inside the user control the text 'Add Item from inside XListBox' appears in the Listbox no problem.如果单击用户控件内的按钮,则文本“从 XListBox 内部添加项目”出现在列表框中没有问题。 If I click the button on the form however, the string 'Add item to XListBox from form' does not get added to the listbox although the Debug.Print does show it in the output window.但是,如果我单击表单上的按钮,尽管 Debug.Print 确实在 output window 中显示了字符串 'Add item to XListBox from form',但不会将其添加到列表框中。 It appears that I am missing something but I have no idea what.看来我错过了一些东西,但我不知道是什么。 Any help would be appreciated.任何帮助,将不胜感激。 Thanks in advance.提前致谢。

Public Class Form1

    Dim lstActions As New XListBox

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        '
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        lstActions.AddItem("Add item to XListBox from form")
    End Sub

End Class

Public Class XListBox ' user control

    Private Sub XListBox_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        '
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ListBox1.Items.Add("Add Item from inside XListBox")
    End Sub

    Public Sub AddItem(sString As String)
        ListBox1.Items.Add(sString)
        Debug.Print(sString)
    End Sub

End Class

Why do you have this in your code there?为什么你的代码中有这个?

Dim lstActions As New XListBox

Surely you added the user control to your form in the designer, like you would any other control.当然,您在设计器中将用户控件添加到表单中,就像您添加任何其他控件一样。 How do you usually access a control that you added to the form in the designer?您通常如何访问在设计器中添加到表单的控件? Basically, you are ignoring the one you added in the designer, ie the one you can see, and you have created another one that you never add to the form, so you can't see it, and that's the one you're adding the items to.基本上,您忽略了您在设计器中添加的那个,即您可以看到的那个,并且您创建了另一个您从未添加到表单中的那个,所以您看不到它,这就是您正在添加的那个的项目。 Don't.不。 Get rid of that field and use the one you added in the designer.摆脱该字段并使用您在设计器中添加的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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