在用户控件之间传递数据 c#

编程入门 行业动态 更新时间:2024-10-28 04:17:39
本文介绍了在用户控件之间传递数据 c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

众所周知,有一些与此类似的解决方案,但我无法用它们解决我的问题.我有两个用户控件:

It's known that there are some solutions similar to this one, but I can't solve my problem with them. I have two user controls:

  • 第一个创建一个 Report 对象.
  • 第二个展示了它.

我有一个链接两个控件的主表单.

I have a main Form that links both controls.

这两个控件是在一个 DLL 中创建的,并添加到像这样的主要形式:

These two controls are created in a DLL, and are added to the main form like this:

//ADDS THE FIRST CONTROL TO THE PANEL CONTROL myDll.controlUserReport userControlA = new myDll.controlUserReport(); panelControl1.Controls.Add(userControlA); userControlA.Dock = DockStyle.Left; //ADDS THE SECOND CONTROL TO THE PANEL CONTROL myDll.controlDocViewer userControlB = new myDll.controlDocViewer(); panelControl1.Controls.Add(userControlB); userControlB.Dock = DockStyle.Fill;

如何将在单击按钮时在第一个控件 controlUserReport 中创建的 Report 对象传递给另一个用户控件 controlDocViewer 以显示它?

How can I pass the Report object, which is created in the first control controlUserReport when I click over a button, to the other user control controlDocViewer to show it?

推荐答案

您应该为此使用事件.在 UserControlA 中声明事件:

You should use events for this. In UserControlA declare the event:

//Declare EventHandler outside of class public delegate void MyEventHandler(object source, Report r); public class UserControlA { public event MyEventHandler OnShowReport; private void btnShowReport_Click(object sender, Report r) { OnShowReport?.Invoke(this, this.Report); } }

在UserControlB中订阅事件并显示报告:

In UserControlB subscribe to the event and show the report:

public class UserControlB { // Do it in Form_Load or so ... private void init() { userControlA.OnShowReport += userControlA_OnShowReport; } private void userControlA_OnShowReport(object sender, Report r) { // Show the report this.ShowReport(r); } }

更多推荐

在用户控件之间传递数据 c#

本文发布于:2023-11-06 15:59:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564145.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控件   数据   用户

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!