父窗口:
private string strValueA = "";
public string StrValueA
{
get
{
return this.strValueA;
}
set
{
this.strValueA = value;
}
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.strValueA = this.textBox1.Text;
Form2 frmchild = new Form2();
frmchild.Owner = this;
frmchild.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
this.strValueA = this.textBox1.Text;
Form2 frmchild = new Form2(this.textBox1.Text);
frmchild.Owner = this;
string returnValue = "";
if (frmchild.ShowDialog() == DialogResult.OK)
{
// 获取子窗口传回的属性值
returnValue = frmchild.Str;
this.textBox1.Text = returnValue;
}
}
子窗口:
// 设置它的变量和属性
private string str;
public string Str
{
get
{
return this.str;
}
set
{
this.str = value;
}
}
// 定义一个父窗口对象
private Form1 frmparent;
// 默认构造函数
public Form2()
{
InitializeComponent();
}
// 构造函数
public Form2(string str)
{
this.str = str;
InitializeComponent();
// 赋文本框为传入的值
this.textBox1.Text = str;
}
private void Form2_Load(object sender, EventArgs e)
{
// 将定义的父窗口对象赋值为子窗口所指向的父窗口
frmparent = (Form1)this.Owner;
// 同时在文本框中显示父窗口的属性值
this.textBox1.Text = frmparent.StrValueA;
}
private void button1_Click(object sender, EventArgs e)
{
this.Str = this.textBox1.Text;
this.DialogResult = DialogResult.OK;
// 从子窗口中传数值给父窗口
// this.Str = "hello";
this.Close();
}