0

I have a small user control having a textbox and a button in it. I have a label in a page which holds the usercontrol. On a button click event of the user control I want to find out the area of user input value and want to display that area in a label on the main page.

UserControl

public partial class WebUserControl1 : System.Web.UI.UserControl
{
   public delegate void myeventhandler(object sender,MyEventArgs e);       

    public event myeventhandler MyEvent;        

     protected void Button1_Click(object sender, EventArgs e)
     {
       int radious= Convert.ToInt32(TextBox1.Text);
       double area = 3.14 * radious * radious;          
       MyEventArgs myeventargs = new MyEventArgs();
       myeventargs.Area = area;
       MyEvent(this, myeventargs);        

    }        
}

public class MyEventArgs : EventArgs
{
    public double Area { set; get; }
}

Main page

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        WebUserControl1 objuc = new WebUserControl1();           
        objuc.MyEvent += new WebUserControl1.myeventhandler(DisplayArea);              
    }

    public void DisplayArea(object sender,MyEventArgs e) 
    {
         Label1.Text   = e.Area.ToString();               
    }
}

But I am getting a NullReferenceError on line

MyEvent(this, myeventargs);
Kenneth
  • 28,294
  • 6
  • 61
  • 84

1 Answers1

1

You must check that MyEvent is not null before triggering it.

if(null != MyEvent)
    MyEvent(this, myeventargs); 
quantdev
  • 23,517
  • 5
  • 55
  • 88
  • I checked it and found out that MyEvent is null so getting the NullReferenceError so if Iuse if condition then MyEvent(this, myeventargs) is not getting call,I want to call it,how to do it?? – RakeshTheStar May 31 '14 at 22:52
  • 1
    It is null because no handler has been attached to the event. Make sure that the button on which you click is the one to which you attached an handler. – quantdev May 31 '14 at 22:57
  • I want to attach the handler in the main page which consuming the UserControl and not in the ButtonClick – RakeshTheStar May 31 '14 at 23:01
  • You will need to use a debugger to find out why. Guess: make sure that `Page_Load()` is being called. – quantdev May 31 '14 at 23:06