【发布时间】:2014-11-21 11:02:58
【问题描述】:
我有一个表单中包含多个项目的列表框。我需要选择列表框项目并单击一个按钮,然后选定的项目应该出现在另一个表单的文本框中。我该怎么做?
单击按钮后,我使用此代码将项目放入表单 1 列表框中。
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();
}
}
我需要选择此列表框中的项目并单击此表单中的更新按钮,它将打开另一个名为 Form2 的表单。我需要从以前的表单 (Form1) 中获取选定的项目,并将其显示在另一个表单 (Form2) 的文本框中。
这是我的第二个表单(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();
}
}
【问题讨论】:
-
在 Stack Overflow 上没有关于如何在两个表单之间交换数据的大约 500 万个类似问题(包括答案!)?