1

I am creating Windows form application and its main form contains a panel. Different user controls are being loaded on that panel on button click.

namespace LearnCSharp
{
    public partial class MainForm : Form
    {
        private void configButton_Click(object sender, EventArgs e)
        {

            var uControllerDashboard = new Controllers.Dashboard();      
            panel.Controls.Add(uControllerDashboard);
            updateNotification("active");           

        }

        private void updateNotification(string state)
        {
            switch (state)
            {
                case  "active" :
                //Do something here
                break;

            }
        }

    }
}

when click config button it loads Dashboard user controller into Panel there is a another apply button in Dashboard userControl. When I click that button I need to call updatNotification method in MainForm Class.

namespace LearnCSharp.Controllers
{
    public partial class Dashboard : UserControl
    {
        private void btnApply_Click(object sender, EventArgs e)
        {
            // Need to call updateNotification method here. 
        }
    }
}

how can I achieve my requirement. I appreciate any help. Thanks.

jsanalytics
  • 13,058
  • 4
  • 22
  • 43
D. Joe
  • 19
  • 1
  • 3
    First you need to mark the method public, then create an instance of MainForm and finally call MainForm.updateNotification () – apomene Nov 29 '17 at 11:00
  • @apomene +1 but could you please change `MainForm.updateNotification` to something like `instance.updateNotification`? Because it looks pretty much like a static-call right now. – Damien Flury Nov 29 '17 at 11:07
  • @apomene's answer whilst technically available, should not be used except in extreme circumstances. Instead use the Events answer below since your control will probably not know the instance that it is associated with. – netniV Nov 29 '17 at 12:21

1 Answers1

2

Use events for that.

Instead of calling the MainForm inside the UserControl, create an event in the UserControl and have the MainForm subscribe that event. Inside the UserControl you just need to trigger the event.

There are many examples on web about this. Just take a look at this:

Hope this helps.

netniV
  • 2,328
  • 1
  • 15
  • 24
bruno.almeida
  • 2,746
  • 1
  • 24
  • 32