user644194
user644194

Reputation: 77

fix System.NullReferenceException in C#

i m developing a website and stuck with System.NullReferenceException . on the master page I m using this code

if (Request.Url.ToString().ToLower().Contains("content.aspx"))
{
    if (Request.Params["ModuleID"].ToString() == null)
    {
        Response.Redirect("Content.aspx?ModuleID=1");
    }
}

when Module Id is blank then it creates null reference exception.

Upvotes: 1

Views: 1722

Answers (2)

Wessel Kranenborg
Wessel Kranenborg

Reputation: 1440

You have to check the Request.Params["ModuleID"] on null. An null does not have a .ToString(), that is why you get this exception. If you use the following code you should not get an NullReferenceException.

if (Request.Url.ToString().ToLower().Contains("content.aspx")) 
{ 
    if (Request.Params["ModuleID"] == null) 
    { 
        Response.Redirect("Content.aspx?ModuleID=1"); 
    } 
}

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503779

Just take out the call to ToString():

if (Request.Params["ModuleID"] == null)
{
    Response.Redirect("Content.aspx?ModuleID=1");
}

Currently you're trying to call ToString on a null reference.

This won't redirect if the ModuleID is present but empty though. You may want:

if (string.IsNullOrEmpty(Request.Params["ModuleID"]))
{
    Response.Redirect("Content.aspx?ModuleID=1");
}

Upvotes: 8

Related Questions