简体   繁体   中英

C# Calling a function on a Form from an Event, outside of this Form class

This has been asked probably many times, but looking through all the other questions I still was not able to solve my issue. I want to update a Datagridview on a form using an update function on this form. The Update function is called by a subscriber.

Overview:

static class MainClass
{
    static void Main()
    {

        // The Main form is called.
        MainForm = new frmMain();
        Application.Run(MainForm);

        //Application.Run(new frmMain());
    }

}

A Delegate

public delegate void Delagate_UpdateDataView();

The subscriber that subscribed to publisher that fires an event every 500 ms.

public class SubscriberFrmMain
{
   // Constructor
    public SubscriberFrmMain()
    {

    }

    // Subscribe to the Publisher

    public void Subscribe(PublisherTimedEvent mUpdateHMIData)  
    {
        //attach listener class method to publisher class delegate object

        mUpdateHMIData.TickUpdateHMIData += UpdateHMIData;
    }

    // The Event, fired when the Publisher raises an event.

    private void UpdateHMIData(PublisherTimedEvent mUpdateHMIData,EventArgs e)   
    // Calling the Update function on the Form MainForm.
    {
        MainClass.MainForm.Process_UpdateDataView(new
        Delagate_UpdateDataView(MainClass.MainForm.UpdateDataView));
    }

}

The Update function in the Form

    public void Process_UpdateDataView(Delagate_UpdateDataView update)
    {
        update();

    }


    public void UpdateDataView()
    {

        try
        {
            TagTableAdapter.Fill(uDataSet.PLC_Tag);
        }
        catch
        {

        }
    }

Updating the TagTableAdapter manually works without any problem. Updating using the subscriber does nothing. Probably there are easier ways to achieve this but I would like to use this type of construction also for other parts of the program.

Thanks for your suggestions.

Event's can only be risen from inside the class. If you could do that it would defeat the purpose of events.You can subscribe to this event from other class tho.

public event EventHandler someEvent;
EventContainer obj = new EventContainer(); 
obj.someEvent += handler;

where handler is a method according to the signature of someEvent. One is able to subscribe to the event from the outside just fine, but it can only be risen from inside the class defining it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM