This is one of the most frequently asked and answered questions here on this forum.
The scenario states that a button will be pressed ... we assume on Form1 ... and that the TextBox.Text in Form1 will be added to the ListBox.Items in Form2.
That there is a button to be pressed implies this update will be performed more than once.
So: Form1 needs access ... repeated access ... to the ListBox on Form2.
How do we accomplish that: well, there are several ways, and, because I am bored with doing it via a Public Property, this time, for variety's sake, and with a 'wing and a prayer' the OP just might be constructively challenged, we'll implement it using a static variable in Form2 that holds a reference to Form2's Listbox.
public partial class Form2 : Form
{
public static ListBox f2ListBox;
public Form2()
{
InitializeComponent();
f2ListBox = listBox1;
}
}
Now how do we use this from Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private ListBox targetListBoxOnForm2;
private void Form1_Load(object sender, System.EventArgs e)
{
new Form2().Show();
targetListBoxOnForm2 = Form2.f2ListBox;
}
private void button1_Click(object sender, System.EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text)) return;
targetListBoxOnForm2.Items.Add(textBox1.Text);
}
}