当前位置:网站首页>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
边栏推荐
猜你喜欢

Codeforces Round #659 (Div. 2)

Recyclerview universal adapter package

Seaweedfs security configuration

Slide the custom control to close the activity control

The stones game

通过Win32API调用另一界面的按钮

HDU 6778 Car (分组枚举-->状压 dp)

Time varying and non time varying

六度空间 bfs

This open source project is super wow, and handwritten photos are generated Online
随机推荐
基辅周边的凄美废墟——切尔诺贝利的安全前往指南!
L2-026 小字辈 (25 分)
Use of Azkaban in task scheduler
Recyclerview sticky (suspended) head
子串分值-超详细版——最后的编程挑战
Recurrence of vulnerability analysis for Cisco ASA, FTD and hyperflex HX
2020-9-14 introduction to advertising system
Nacos environmental isolation
Summary after the 2009 ICPC Shanghai regional competition
PGP在加密技术中的应用
C#中Linq常用用法
2019.10.27训练总结
蛇形填数
Web vulnerability manual detection and analysis
51nod1277 字符串中的最大值【KMP】
IIS服务器相关错误
山科 的C语言2018练习题(电信)
The stones game
If I were in Beijing, where would it be better to open an account? In addition, is it safe to open an account online now?
Shanke's C language 2018 exercise (Telecom)

