当前位置:网站首页>C#窗体向另一个窗体实时传值
C#窗体向另一个窗体实时传值
2022-06-29 09:26:00 【zlbcdn】
1、功能展示
有时需要将子界面的内容传递到父界面,方法有好几种。经常用的是通过委托实现。具体的效果如下:
![]()
【说明】点击父界面上“打开子界面”button,则会弹出子界面。父界面与子界面如上图所示。
![]()
【说明】在子界面的textBox框内输入待返回至父界面的内容,点击“将内容返回”button,则父界面的textBox将会展示返回的内容。具体如上图所示
2、代码分析
里面应用了委托(delegate)和事件(event)。委托就是前端开发中最常用的“回调方法”(callback),event是一种注册机制,将动作与委托关联。
为了实现以上功能,首先先编写子窗体的定义。代码如下:
public partial class Form2 : Form { //第二步:声明一个委托类型的事件 public event setTextValue setFormTextValue; public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //第三步:准备相关数据。 setFormTextValue(this.textBox1.Text); } } // 第一步:声明一个委托。(根据自己的需求) public delegate void setTextValue(string textValue);
第一步:先在子窗体中定义一个委托。根据实际需求定义委托
第二步:在子窗体中声明一个event,将委托与动作关联
第三步:在具体的事件中实现event
以上三步参见Form2的代码
父窗体的代码如下:
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 form2 = new Form2(); //第四步:初始化事件 form2.setFormTextValue += new setTextValue(form2_setFormTextValue); form2.Show(); } //第五步:实现事件 void form2_setFormTextValue(string textValue) { //具体实现。 this.textBox1.Text = textValue; } }
在父窗体的具体实现中分为2步:
第四步:在定义子窗体时,声明子窗体的事件
第五步:实现具体的事件
以上,就是全部的内容
3、功能分析
通过委托的方式,优点:松耦合。
4、源码下载
【说明】因为CSDN会把旧代码下载的门槛自动提高至50金币,所以我把代码共享到百度云。具体链接如下
下载链接 提取码: zkeu
边栏推荐
猜你喜欢
随机推荐
51nod1277 maximum value in string [KMP]
Serpentine filling number
Web vulnerability manual detection and analysis
2019.10.27 training summary
Picture verification code control
Rikka with Cake(线段树+线段树)
QGIS mapping
1146 topological order (25 points)
2019.10.30 learning summary
1099 Build A Binary Search Tree (30 分)
Shanke's C language 2018 exercise (Telecom)
通过Win32API调用另一界面的按钮
September 25, 2020 noncopyable of boost library for singleton mode
Use of Azkaban in task scheduler
蛇形填数
Analyze in detail the PBOT mining virus family behavior and the principle of exploited vulnerabilities, and provide detailed protection suggestions for the blue army
Application of Pgp in encryption technology
1021 Deepest Root (25 分)
2019.10.27训练总结
2020-09-21 visual studio header file and Library Directory configuration










