3
votes

I have a listbox with multiple items in a form. I need to select listbox item and click a button and then selected item should appear in another form's textbox. How can I do this?

I use this code to put items to my form 1 list box after I click a button.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();                
    }

    private void button1_Click(object sender, EventArgs e)
    {
        SqlConnection conn2 = new SqlConnection(
            "<path>\\Database1.mdf\";Integrated Security=True");
        conn2.Open();

        ArrayList al = new ArrayList();
        SqlCommand commandtwo = new SqlCommand(
            "SELECT name FROM [dbo].[Table2]", conn2);
        SqlDataReader dr2 = commandtwo.ExecuteReader();

        while (dr2.Read())
        {
            al.Add(dr2[0].ToString());
        } 

        try
        {
            listBox1.Items.Clear();
            listBox1.Items.AddRange(al.ToArray());
            conn2.Close();
        }
        catch (Exception) 
        {}
    }

    public void button2_Click(object sender, EventArgs e)
    {         
        Form2 f2 = new Form2();
        f2.Show();
    }
}

I need to select item in this listbox and click Update button in this form, it will open another form called Form2. I need to get selected item from previous form (Form1) and show it in a textbox in another form (Form2).

This is the code of my second form (Form2)

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        Form1 f1 = new Form1();
        textBox1.Text = f1.listBox1.SelectedItem.ToString();
    }
}
2
Aren't there about 5 million similar questions (including answers!) out there on Stack Overflow about how to exchange data between two forms?Uwe Keim

2 Answers

4
votes

There's many ways to do it. One is to have public property on first form that you access from the other form. But as said, this is only one approach (you could use events, pass value in overloaded constructor, etc.)

// Form1
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    SelectedItem = (sender as ComboBox).SelectedItem.ToString();
}

private void button_Click(object sender, EventArgs e)
{
    var frm2 = new Form2() { Owner = this };
    frm2.Show();
}

public string SelectedItem { get; private set; }

And then...

// Form2
protected override void OnActivated(EventArgs e)
{
    base.OnActivated(e);
    textBox1.Text = (Owner as Form1).SelectedItem;
}
0
votes

You have to pass the value to the Form2 in the constructor.

public Form2(string value)
{
     InitializeComponent();
     textBox1.Text = value;
}

In your Form1 just call it like this:

// get the item from listbox into variable value for example
Form2 = new Form2(value);
f2.Show();