winform窗口传值问题

最近遇到一个winform子窗口刷新父窗口中控件的问题,解决方案如下:

 

Form1为父窗体,Form2为子窗体

Form1中的代码:
private string strValue;

public string StrValue        //可以定义一个控件的text值或其他来来进行控件的设置
{
get { return strValue; }
set { strValue = value; }
}
private void btnShow_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();

//子窗体返回值给父窗体
form2.Owner = this;;//重要的一步,主要是使Form2的Owner指针指向Form1

form2.ShowDialog();
MessageBox.Show(StrValue);//显示返回的值

}
Form2中的代码:
private void btnclose_Click(object sender, EventArgs e)
{
Form1 form1 = (Form1)this.Owner;//把Form2的父窗口指针赋给lForm1
form1.StrValue = "子窗体成功返回值给父窗体!";//使用父窗口指针赋值

this.Close();
}

 

网上顺便还看到了子窗口调用父窗口的值,也相当于父窗口向子窗口传值吧。

总结如下:

1 全局变量
只要把变量描述成static就可以了,在form2中直接引用form1的变量,代码如下:
在form1中定义一个static变量public static int i= 9 ;
Form2中的钮扣按钮如下:
private void button1_Click(object sender, System.EventArgs e)
{textBox1.Text = Form1.i.ToString();}

 

2 父窗口传值给子窗口(Form1为父窗体,Form2为子窗体)
代码如下:

Form1中的代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}


private void btnShow_Click(object sender, EventArgs e)
{

//父窗体传值给子窗体
Form2 form2 = new Form2();
form2.String1 = "成功传值给Form2窗体!";
form2.SetValue();
form2.ShowDialog();
}
Form2中的代码:

private string String;

public string String1
{
get { return String; }
set { String = value; }
}
public void SetValue()
{
this.lblText.Text = String1;
}

posted on 2010-08-25 09:07  kafony  阅读(828)  评论(2编辑  收藏  举报

导航