1,父窗体传值到子窗体:通过子窗体的构造函数;
FORM1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 frm;
private void Form1_Load(object sender, EventArgs e)
{
frm = new Form2();
//frm.receive += new EventHandler(f2_accept);
//
frm.receive += new EventHandler(
(sender1, e1) =>
{
textBox1.Text = frm.Form2Value;
}
);
}
private void button1_Click(object sender, EventArgs e)
{
//Form2 frm = new Form2(textBox1.Text);
//if (frm.ShowDialog() == DialogResult.OK)
//{
// textBox1.Text = frm.TextBoxValue;
// frm.Close();
//}
frm.Show ( );
}
void f2_accept(object sender, EventArgs e)
{
//事件的接收者通过一个简单的类型转换得到Form2的引用
//Form2 f2 = sender as Form2;
if (frm != null)
//接收到Form2的textBox1.Text
this.textBox1.Text = frm.Form2Value;
}
}
FORM2:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public Form2(string value)
{
InitializeComponent();
TextBoxValue = value;
}
private string textBoxvalue;
public string TextBoxValue
{
//get { return textBox1.Text; }
//set { textBox1.Text = value; }
get { return textBoxvalue; }
set { textBoxvalue = value; }
//get;
//set;
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//this.DialogResult = DialogResult.OK;
//textBoxvalue = textBox1.Text;
//if ( accept != null )
//{
// accept (this , EventArgs.Empty ); //当窗体触发事件,传递自身引用
//}
if (receive != null)
{
receive(this, EventArgs.Empty);
}
}
public string Form2Value
{
get
{
return this.textBox1.Text;
}
set
{
this.textBox1.Text = value;
}
}
public event EventHandler accept;
public event EventHandler receive;
private void textBox1_TextChanged(object sender, EventArgs e)
{
receive(this, EventArgs.Empty);
}
}