2

I have a page.aspx that reads the query string, and if the QueryString is something like page.aspx?id=1, it runs some code.

However, I want it to simply ignore that code if no QueryString is specified. If I simply go to page.aspx. Right now, the only code I have on page load is

if (Request.QueryString["id"].Equals("1"))
  {
     //Do something
  }

That works if I go to page.aspx?id=1. However, simply going to page.aspx gives me this error:

object reference not set to an instance of an object

How can I load the page with no query string?

John Saunders
  • 159,224
  • 26
  • 237
  • 393
Boxiom
  • 2,185
  • 6
  • 38
  • 50
  • 1
    Your problem is that you are not also checking for nulls: `Request.QueryString["id"] != "" && Request.QueryString["id"] != null)` – stripthesoul May 13 '14 at 12:50
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders May 13 '14 at 13:05

5 Answers5

8

You need to check for nulls

if (Request.QueryString["id"] != null && Request.QueryString["id"].Equals("1"))
{
   //Do something
}
pbjork
  • 556
  • 4
  • 10
3

You can do this:

if(Request.QueryString.Length != 0)
{
   ...
}

If you try to access elements which are not present, you'll receive an exception. So, since QueryString has a property of Length, checking it against 0 means there is no query string at all.

Else if you want to know that only if id key isn't present, you can do this:

if(Request.QueryString.AllKeys.Contains("id"))
{

}
Amit Joki
  • 56,285
  • 7
  • 72
  • 91
1

This will cover any null reference issues or when there simply is an empty query string

if (Request.QueryString != null && Request.QueryString["id"] != null && Request.QueryString["id"] == "1")
{
//do work
}
Sven Grosen
  • 5,547
  • 3
  • 29
  • 49
1

Try this:

if (Request.QueryString["id"] != null && Request.QueryString["id"].Equals("1"))
{
 //Do something
}

Another way :

string id = Request.QueryString["id"] ?? "";
if(id == "1")
{
     //Do something
}
Ranjan Kumar
  • 457
  • 1
  • 6
  • 21
0

Whenever you see this error :

     object reference not set to an instance of an object

Know that you are checking for something that is null or simply doesn't exist

so try this :

    if(Request.QueryString["id"] != null)
     {
        if (Request.QueryString["id"].Equals("1"))
        {
               //Do something
        }
     }
Ramy M. Mousa
  • 5,301
  • 3
  • 37
  • 43