您的位置:首页 > 编程语言 > C#

C# Winfrom窗体之间传值

2017-07-29 21:58 399 查看
有任何错误之处请多指正。
多个WinForm窗体之间需要进行数据的传递,如何进行传递,如何更好的进行传递。
窗体之间传值有五种方式(重点说委托)
1.使用构造函数进行实例化时进行传值(无demo);
2.使用Tag进行传值(无demo);
3.使用静态资源进行传值(无demo);
4.通过属性进行传值(无demo);
5.通过委托进行传值

委托和lambda、Action、Func在之后的委托与事件、Lambda表达式等均会进行讲解。

委托demo:
说明:
Form1有一个Textbox和Button
Form2有一个TextBox和三个Button


//Form1中Button的Click事件
private void btnSend_Click(object sender, EventArgs e)
{
//获取TextBox的值
string inputValue = textBox1.Text.Trim();
//创建窗体
Form2 demoFrom = new Form2();
//委托进行窗体传值
demoFrom.GetValue= delegate() {
return inputValue; };
//委托进行获取值
demoFrom.SendValue = delegate(string a) {
this.textBox1.Text=a;
};
//委托进行获取并传递值
demoFrom.GetAndSend = delegate(string a) {
string formValue = this.textBox1.Text;
this.textBox1.Text = a;
return formValue;
};
//展示
demoFrom.Show();
}

//Form2的三个委托
public Func<string> GetValue;

public Action<string> SendValue;

public Func<string, string> GetAndSend;

private void btnGet_Click(object sender, EventArgs e)
{
textBox1.Text = this.GetValue();
}

private void btnSend_Click(object sender, EventArgs e)
{
textBox1.Text += "。。。发送,走你";
//不操作From进行From的TextBox的修改
this.SendValue(textBox1.Text);
}

private void btnGetAndSend_Click(object sender, EventArgs e)
{
this.textBox1.Text=this.GetAndSend("既获取,又发送");
}


Effect Picture:
![这里写图片描述](https://img-blog.csdn.net/20170729215826672?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQva2FuZ194dWFu/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息