简体   繁体   中英

Custom event handler not getting initialized

Following is the Code i am 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 Onclick function within ImpersonatedTab class it returns error saying TriggerSaveSetting is null

I initialize this call like

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

i have created events earlier, but am not able to figure out whats wrong with this one.. i am sure should be some silly mistake.

One possible case where this could happen is if you try to call the event from within the constructor of the ImpersonatedTab class. There where you put those ... . Also it is a good practice to check if the event handler has been initialized before calling it.

Change your code to this:

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

You can now set a breakpoint on the add accessor and SaveData() and verify that event subscription is working correctly. If you do see the add accessor getting called but still get a null for handler then there's a problem with the object reference.

You are trying to invoke the TriggerSaveSetting event handlers before any handler was attached to it. Make sure, to check, the event has been some handlers attached:

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

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