Loading ...

Common reasons of Object Reference not set to an instance of an object | CodeAsp.Net

Common reasons of Object Reference not set to an instance of an object

 /5
0 (0votes)

I have faced this exception several times and spent lot of time to solve this problem, Basically when I was beginner in progamming.

I think this error comes in different conditions, but iwould like to discuss the common reasons which i have faced during my programming life.

Scope Declaration:

When we used a variable which scope defined locally and used like global.Suppose we define a variable of type string in a event and use at different event.for eg.

public partial class Class1

{

    protected void Page_Load(object sender, EventArgs e)
            {

            }

        protected void Button1_Onclick(object sender, EventArgs e)
            {
                string strName=string.empty; //variable scope is local
            }

        protected void Button2_Onclick(object sender, EventArgs e)
            {
                strName="ABC"; //assigned the value in variable which scope does not exist here
            }

}

Adding the key value in web.config:

When we used a key value on the aspx page and value not defined at web.config, then it gives above error.

so that i would like to suggest programmers to when it gives error like that, then make sure whether the key value which has used at aspx page is define in web.config.

eg.

public partial class Class1

{

      protected void Page_Load(object sender, EventArgs e)
            {     

            }

        protected void Button1_Onclick(object sender, EventArgs e)
            {
                 string fromEmail = ConfigurationManager.AppSettings["fromEmail"].ToString();//using key value but not added in web.configso it gives error
            }    

}

so avoid this, you have to defined the key value in web.config like :

<appSettings>

<add key="fromEmail" value="abc@abc.com"/>

</appSettings>

Hope this will help...

Comments (no comments yet)

Top Posts