I have a form with a text box and a form with a list box. I would like to be able to push a button on the form with the text box and have it be added to a list box. any help?

Dani AI

Generated

: good starting question — 's single-line solution and 's Try/Catch are the simplest fixes for a same-form scenario or a quick cross-form call. For a robust, maintainable solution when the TextBox and ListBox live on different forms, avoid directly reaching into another form's controls from code-behind unless you have a clear reference to the displayed instance.

Preferred patterns (clear and safe)

  • Expose a small public method on the list form that accepts a string and performs validation (trim, non-empty, optional duplicate check) before updating the UI.
  • Or share a single data collection bound to the ListBox (for example a BindingList(Of String)) so both forms mutate the same model and the UI updates automatically.
  • Or raise an event from the text form that the list form subscribes to, keeping forms decoupled.

Example (data-binding approach)

' place this shared list in a module or in the main form
Public Shared SharedItems As New System.ComponentModel.BindingList(Of String)

' in the list form: bind once (e.g., in Load)
ListBox1.DataSource = SharedItems

' in the text form's button handler: validate then add
If Not String.IsNullOrWhiteSpace(TextBox1.Text) Then
    SharedItems.Add(TextBox1.Text.Trim())
End If

Troubleshooting notes

  • Do not create a new FormB instance just to add an item — that writes to an invisible copy. Call the method on the same instance the user sees, or use the shared-data/event approaches above.
  • If updating the ListBox from a background thread, use Invoke/BeginInvoke.
  • Avoid swallowing exceptions: catch specific exceptions if needed and show useful messages rather than an empty Try/Catch. These patterns keep the UI responsive and the code easier to test and extend.

Recommended Answers

All 3 Replies

this will do that:

ListBox1.Items.Add(TextBox1.Text)

yes it is very simple, for example you have a formA having textbox and formB has a listbox , now put this coding at you button.

Try
            formB.listbox1.items.add(textbox1.text)
        Catch ex As Exception
            MsgBox(Err.Description)
        End Try

this will solve your prob .
Regards

thanks for the help :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.