Passing data between usercontrols c#

蹲街弑〆低调 提交于 2020-01-11 09:44:51

问题


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:

  • The first one makes a Report object.
  • The second one shows it.

I have a main Form that links both controls.

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;

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?


回答1:


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);
    }
}

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);
    }
}


来源:https://stackoverflow.com/questions/44716233/passing-data-between-usercontrols-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!