[c#] An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

What does this error mean?, I keep getting this error, it use to work fine and it just started throwing this error.... any help?

img1.ImageUrl = ConfigurationManager.AppSettings.Get("Url").Replace("###", randomString) 
 + Server.UrlEncode(((System.Web.UI.MobileControls.Form)Page.FindControl("mobileForm")).Title);

An exception of type 'System.NullReferenceException' occurred in MyProject.DLL but was not handled in user code

Additional information: Object reference not set to an instance of an object.

This question is related to c# mobile-website

The answer is


It means somewhere in your chain of calls, you tried to access a Property or call a method on an object that was null.

Given your statement:

img1.ImageUrl = ConfigurationManager
                    .AppSettings
                    .Get("Url")
                    .Replace("###", randomString) 
                + Server.UrlEncode(
                      ((System.Web.UI.MobileControls.Form)Page
                      .FindControl("mobileForm"))
                      .Title);

I'm guessing either the call to AppSettings.Get("Url") is returning null because the value isn't found or the call to Page.FindControl("mobileForm") is returning null because the control isn't found.

You could easily break this out into multiple statements to solve the problem:

var configUrl = ConfigurationManager.AppSettings.Get("Url");
var mobileFormControl = Page.FindControl("mobileForm")
                            as System.Web.UI.MobileControls.Form;

if(configUrl != null && mobileFormControl != null)
{
    img1.ImageUrl = configUrl.Replace("###", randomString) + mobileControl.Title;
}

It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1 is null or ConfigurationManager.AppSettings.Get("Url") is returning null.