问题一: 为什么没方法二在按下Form2的按键button1时老是显示的是Form1中初始化时str的值(此处为""),不是在按下Form1的button1时候已经改变了str的值了吗?另外就算把代码写在构造函数里还是不行,Form1的构造函数代码如下:
public Form1()
{
textbox texbox1 = new textbox();
str=texbox1.text;
InitializeComponent();
}
方法一(成功了)
窗体Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.str = this.textBox1.Text;
form2.Show();
}
}
窗体Form2
public partial class Form2 : Form
{
public string str = "";
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 =new Form1();
this.textBox2.Text=str;
}
}
方法二(失败了)
窗体Form1
public partial class Form1 : Form
{
public string str = ""; //主要的与方法一不同的地方
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
str=this.textbox1.text;
form2.Show();
}
}
窗体Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 =new Form1();
this.textBox2.Text = form1.str;
}
}
问题二:
另一种方法(成功了)
窗体from1
public partial class Form1 : Form
{
public string str;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Owner = this;
str = this.textBox1.Text;
form2.Show();
}
}
窗体Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 =(Form1)this.Owner; //为什么不能写成 Form1 form1=this.Owner;(this在这指Form2的引用,Form2窗口本来就是被Form1所拥有,this.Owner不就是指的Form1吗?干嘛还要强行转换啊!) 这可能是我对Owner不太了解吧,MSDN只说了些现象(如Form1最小化Form2也最小化)可实质上Owner怎样的呢,因为我看到似乎此处Form1不用创建实例就能访问自身的成员: 如下面的form1.str
this.textBox2.Text = form1.str;
}
}
拜托了各位大侠! 这些问题困扰我好久了。