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();
}
}