0
votes

I have a user control (XListBox) with a listbox (ListBox1) and a button on it. The user control is on a form (Form1) which also has a button on it. 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. 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. 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
1
As jmcilhinney said, use the NAME of the UserControl that is on your form already. By default, if your UserControl is called "XListBox", then the first one you dropped on the form would be called "XListBox1". If you haven't changed the name, then in your click handler you'd simply write XListBox1.AddItem("something"). - Idle_Mind

1 Answers

1
votes

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, i.e. 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.