'Add combobox items from another usercontrol form using textbox

I have a usercontrol form named "ucSETTINGS", where there is a textbox and once the button was clicked, the text inside the textbox will be added to the combobox from another usercontrol form name "ucITEMS"

I tried this code but it's not working (cboCategory is the name of the combobox from ucITEMS, txtNAME is the textbox from ucSETTINGS)

Private Sub btnSAVE_Click(sender As Object, e As EventArgs) Handles btnSAVE.Click
   Dim category As New ucITEMS()
   category.cboCATEGORY.Items.Add(txtNAME.Text)
End Sub

Can someone help me?



Solution 1:[1]

In this sort of situation, the user controls don't know about each other by default and it should stay that way. The source UC just exposes an interface and lets whomever is watching use that as it sees fit. That means raising an event when something happens and exposing required data via properties, e.g.

Public Class SourceControl

    Public ReadOnly Property TextBox1Text As String
        Get
            Return TextBox1.Text
        End Get
    End Property

    Public Event Button1Click As EventHandler

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        OnButton1Click(EventArgs.Empty)
    End Sub

    Protected Overridable Sub OnButton1Click(e As EventArgs)
        RaiseEvent Button1Click(Me, e)
    End Sub

End Class

The Text of the TextBox is exposed via a property and, when the user clicks the Button, the UC raises an event.

The destination UC provides an interface for new items to be provided but it adds them to its own ComboBox, e.g.

Public Class DestinationControl

    Public Sub AddItemToComboBox1(item As Object)
        ComboBox1.Items.Add(item)
    End Sub

End Class

The form then plays go-between, handling the event, getting the property and calling the method:

Private Sub SourceControl1_Button1Click(sender As Object, e As EventArgs) Handles SourceControl1.Button1Click
    DestinationControl1.AddItemToComboBox1(SourceControl1.TextBox1Text)
End Sub

Obviously you would use something more specific and appropriate than my generic naming.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John