2 个UserControl 的传值问题
问题描述:有2个UserControl:UserControl1 里有一个Button,UserControl2 里面有一个TextBox,这2个控件都加载到了主窗体Form1 上。要求的是,点击 UserControl1 的button 显示 UserControl2中TextBox输入的内容。
一般来讲有2种方式:
1. 公开属性
2. 声明事件
来看看这2种方式的操作代码:
1. 公开2个UserControl的属性。并在Form1中使用

public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); } public Button Btn // Define Btn as public { get { return this.button1; } } }

public partial class UserControl2 : UserControl { public UserControl2() { InitializeComponent(); } public TextBox textbox // define textbox as public { get { return this.textBox1; } } }
在From1中注册Button的事件

public partial class Form1 : Form { public Form1() { InitializeComponent(); this.userControl11.Btn.Click += new EventHandler(Btn_Click); } void Btn_Click(object sender, EventArgs e) { MessageBox.Show(this.userControl21.textbox.Text); } }
2. 声明事件

public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); } public event EventHandler BtnClick; //define one public Click event. private void button1_Click(object sender, EventArgs e) { BtnClick(sender, e); // just do it. } }

public partial class UserControl2 : UserControl { public UserControl2() { InitializeComponent(); } public event Action<string> GetText; //define one action to get textbox's text value private void textBox1_TextChanged(object sender, EventArgs e) { GetText(textBox1.Text); // Get this text after input. } }
在Form1中调用

public partial class Form1 : Form { public Form1() { InitializeComponent(); this.userControl21.GetText += new Action<string>(userControl21_GetText); // register gettext event. this.userControl11.BtnClick += new EventHandler(userControl11_Click); // Register Click event. } string text = null; void userControl11_Click(object sender, EventArgs e) // implement it { MessageBox.Show(text); } void userControl21_GetText(string obj) // implement it. { text = obj; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
2009-10-29 Excel 二次开发系列(8):报表服务实例