Custom event handler does not receive initialization

Below is the code I'm using

class ImpersonatedTab : System.Windows.Forms.TabPage { Credentials _cred = new Credentials(); public delegate void Savesetting(TabData Tb); public event Savesetting TriggerSaveSetting; public ImpersonatedTab(TabData tb) { ........ } private void SaveData() { TriggerSaveSetting(_tabdata); } private Onclick() { SaveData(); } } 

When I call the Onclick function in the ImpersonatedTab class, it returns an error saying that TriggerSaveSetting is null

I initialize this call, for example

 ImpersonatedTab Tab = new ImpersonatedTab(tb); Tab.TriggerSaveSetting += new ImpersonatedTab.Savesetting(Tab_TriggerSaveSetting); 

I have created events before, but I can’t understand what is wrong with this. I am sure it must be a stupid mistake.

+4
source share
3 answers

One of the possible cases when this can happen is to try to trigger an event from the constructor of the ImpersonatedTab class. Where you put those ... It is also recommended to check if the event handler was initialized before it was called.

+2
source

Change the code as follows:

  public delegate void Savesetting(TabData Tb); private Savesetting saveSettingDlg; public event Savesetting TriggerSaveSetting { add { saveSettingDlg += value; } remove { saveSettingDlg -= value; } } private void SaveData() { var handler = saveSettingDlg; if (handler != null) handler(_tabdata); } 

Now you can set a breakpoint in add accessor and SaveData () and make sure that event subscription is working correctly. If you see that add accessor receives the call, but still gets zero for the handler, then there is a problem with the object reference.

+2
source

You are trying to call TriggerSaveSetting event handlers before a handler is attached to it. Make sure that some handlers are attached to check the event:

 private void OnTriggerSaveSetting(_tabdata) { if (TriggerSaveSetting != null) TriggerSaveSetting(_tabdata); } 
+1
source

Source: https://habr.com/ru/post/1336277/


All Articles