How to send a date from a list to a textbox of another form

I have a list with multiple items in a form. I need to select a list item and click a button, and then the selected item should appear in a textbox of another form. How can i do this?

I am using this code to put items in my list of 1 forms after a button is clicked.

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 an item in this list and click the refresh button on this form, it will open another Form2. I need to get the selected item from the previous form (Form1) and show it in a textbox in another form (Form2).

This is the code for 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();
    }
}

      

+3


source to share


2 answers


There are many ways to do this. One of them is to have state property in the first form, which you access from the other form. But as said, this is only one approach (you can use events, pass a value in an 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;
}

      

+4


source


You need to pass the value to 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();

      

0


source







All Articles