Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an event in a dll and handling the event in a Form

Tags:

c#

.net

I have created a DLL using the following code. I have compiled this code as a DLL.

namespace DllEventTrigger
{
    public class Trigger
    {
        public delegate void AlertEventHandler(Object sender, AlertEventArgs e);

        public Trigger()
        {

        }

        public void isRinging()
        {
            AlertEventArgs alertEventArgs = new AlertEventArgs();
            alertEventArgs.uuiData = "Hello Damn World!!!";
            CallAlert(new object(), alertEventArgs);
        }
        public event AlertEventHandler CallAlert; 
    }

    public class AlertEventArgs : EventArgs
    {
        #region AlertEventArgs Properties
        private string _uui = null;
        #endregion

        #region Get/Set Properties
        public string uuiData
        {
            get { return _uui; }
            set { _uui = value; }
        }
        #endregion
    }
}

Now I'm trying to handle the event triggered by this dll in a forms application with this code.

namespace DLLTriggerReciever
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Trigger trigger = new Trigger();
            trigger.isRinging();
            trigger.CallAlert += new Trigger.AlertEventHandler(trigger_CallAlert);
        }

        void trigger_CallAlert(object sender, AlertEventArgs e)
        {
            label1.Text = e.uuiData;
        }
    }
}

My problem i'm not sure where i went wrong. Please suggest.

like image 851
Chandra Eskay Avatar asked Dec 10 '25 21:12

Chandra Eskay


1 Answers

You need to assign your event handler before the event is actually fired, otherwise the code will throw a NullReferenceException.

trigger.CallAlert += new Trigger.AlertEventHandler(trigger_CallAlert);
trigger.isRinging();

Additionally, it's a recommended practice to check first, whether there are handlers assigned:

var handler = CallAlert; // local variable prevents a race condition to occur

if (handler != null) 
{
  handler(this, alertEventArgs);
}
like image 113
Gene Avatar answered Dec 12 '25 10:12

Gene



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!