// Form1
// I have a text box and I want the value to pass onto a text box on form 2
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
}
// Form2
private Form1 otherForm;
private void Form2_Load(object sender, EventArgs e)
{
string test = textBox1.Text;
otherForm.textBox1.Text = test;
}
当我尝试将值传递到表单 2 上的文本框时,它说“调用的目标已抛出异常。”
我也已将保护更改为公开,但我无法成功传递字符串。
请您参考如下方法:
实现这一点的最简单方法是将信息传递给第二种形式的构造函数。这样您就不需要公开文本框。
在 Form2 中:
// Constructor
public Form2 (string message)
{
InitializeComponent(); // Call this first, as it creates the forms controls
textBox1.Text = message;
}
在 Form1 中:
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(textbox1.Text);
form2.Show();
}
顺便说一句,您正在将字符串从 Form2 传递到 Form1(根据需要以相反的方式)并且您永远不会初始化变量 otherForm .它将始终具有默认值 null。
