窗口间传值方法
方法一: 利用窗口的初始化,来传递参数,这种只适用一个窗口打开另一个窗口,在新窗口中传入参数。
Form1.cs
String s="123";
Form2 f2=new f2(s);
f2.show();
Form2.cs
public Form2(string s)
{
InitializeComponent();
Button1.text=s;
}
这时窗口2的button按钮的值就是s的值123。
方法二:利用ShowDialog的返回值判定子窗口是否销毁,然后把子窗口的属性传递到form1中。
Form1.cs
private string m_IP;
public string IP
{
get { return m_IP; }
set { m_IP = value; }
}
private string m_content;
public string Content
{
get { return m_content; }
set { m_content = value; }
}
private string m_ID;
public string ID
{
get { return m_ID; }
set { m_ID = value; }
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
if (frm.ShowDialog() == DialogResult.OK)
{
IP = frm.IP;
Content = frm.Content;
ID = frm.ID;
button1.Text = IP;
}
}
private string m_IP;
public string IP
{
get { return m_IP; }
set { m_IP = value; }
}
private string m_content;
public string Content
{
get { return m_content; }
set { m_content = value; }
}
private string m_ID;
public string ID
{
get { return m_ID; }
set { m_ID = value; }
}
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
IP = textBox1.Text;
Content = textBox2.Text;
ID = textBox3.Text;
this.DialogResult = DialogResult.OK; //让这个窗口的DialogResult的值为OK当这时触发form1中的if (frm.ShowDialog() == DialogResult.OK)成功。
this.Close();//关闭
}
例子在百度网盘有下载: