Search code examples
c#winformsuser-controlsreport

Passing data between usercontrols 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:

  • 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?

enter image description here


Solution

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