111,129
社区成员
发帖
与我相关
我的任务
分享在WinForm之间传值有很多种方法,在这里我用的是delegate and event进行传值.
新建一个WindowsApplication,创建两个WinForm.其实它们就是两个类.
每个WinForm中各加入一个Button和一个TextBox.
在WinForm2中写入代理和事件(delegate and event)如下:
//代理声明
public delegate void SendMessage(string str);
//事件声明
public event SendMessage SendEvent;
private void btnSend_Click(object sender, EventArgs e)
{
//调用事件
SendEvent(textBox1.Text);
}
在WinForm1中写入如下代码:
private void btnShow_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
//Form2事件注册
f2.SendEvent+=new Form2.SendMessage(GetMessage);
f2.Show();
}
//代理调用的方法
public void GetMessage(string str)
{
textBox1.Text = str;
}
在点击WinForm1的Button弹出WinForm2后,在WinForm2中文本框输入文字,然后点击按钮,信息将会立刻发送到WinForm1,并显示出来.1:新建两个窗口: Form1,Form2;
2:打开Form2,添加一个textBox:textBox1;
添加一个Button:button1;
然后添加一个构造函数:
//定义一个变量,用来传值。
public string returnValue ;
public Form2(string txtValue)
{
InitializeComponent();
this.textBox1.Text = txtValue;
}
然后在button1的单击事件中添加如下代码:
private void button1_Click(object sender, EventArgs e)
{
returnValue = this.textBox1.Text;
this.Close();
}
3:Form1中添加一个textBox:textBox1;
添加一个Button:button1;
然后在button1的单击事件中添加如下代码:
private void button1_Click(object sender, EventArgs e)
{
string txtValue = this.textBox1.Text;
Form2 f2 = new Form2(txtValue);
f2.ShowDialog();
this.textBox1.Text = f2.returnValue;
}
Form1 中 (父窗口:)
public class Form1 : System.Windows.Forms.Form {
private System.Windows.Forms.Button btnOpen;
public System.Windows.Forms.TextBox txtContent;
//注意是
public ........ ........ [STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnOpen_Click(object sender, System.EventArgs e)
{
Form2 frm=new Form2(this);
frm.ShowDialog();
}
}
Form2中(子窗口)
public class Form2 : System.Windows.Forms.Form {
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox txtValue;
private Form _parentForm=null;
public Form2() {
InitializeComponent();
}
public Form2(Form parentForm)
{ InitializeComponent();
this._parentForm =parentForm;
} ........ ........ 更新父窗口中文本框中的值!
private void button1_Click(object sender, System.EventArgs e)
{
((Form1)_parentForm).txtContent.Text =this.txtValue .Text ;
}
public Form1(string str)
{
InitializeComponent();
this.label1.Text = str;
}
