Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 320
dbz Avatar asked Apr 08 '26 02:04

dbz


1 Answers

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);
    }
}
like image 164
Romano Zumbé Avatar answered Apr 09 '26 16:04

Romano Zumbé



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!