Webmaster Forums Banner Professional Hosting from Just Host
Welcome Guest Search | Active Topics | Members | Log In | Register

Anonymous Delegate in .net Options
kirshana
Posted: Thursday, May 22, 2008 4:48:20 PM
Rank: Advanced Member
Groups: Member

Joined: 1/31/2008
Posts: 80
Points: 143
Location: India
Hi

I am defining the anonymous method in asp.net page

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

public _Default()
{
btnTest.Click += delegate(object sender, EventArgs e)
{
Response.Write("HI");
};
}
}

Here btnTest is the name of a button

when I run this program I am getting error.



"Object Reference is not set to an instance of an object"



Regards

Sponsor
Posted: Thursday, May 22, 2008 4:48:20 PM
hari
Posted: Thursday, May 22, 2008 4:57:35 PM
Rank: Advanced Member
Groups: Member

Joined: 3/31/2008
Posts: 61
Points: 183
Location: NY
of course you will get that error , because page constructor called in a very early stage , and the button will bot be initialzed yet , even the Response object will not be ready !

instead you need to move the code to Page_Init , with some modifications to the paramters name to avoid the naming conflict as follows:



Code:
   protected void Page_init(object sender, EventArgs e)
        {
            btnTest.Click += delegate(object BtnSender, EventArgs Btne)
            {
                Response.Write("HI");
            };
        }
Users browsing this topic
Guest


Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

Main Forum RSS : RSS

ASPNET Theme created by Boskone (Dan Ferguson)
Powered by HaqTech.Com
Copyright © 2003-2006 Yet Another Forum.net. All rights reserved.
This page was generated in 0.618 seconds.