Вопрос

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?

Это было полезно?

Решение

You need to check for nulls

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

Другие советы

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"))
{

}

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
}

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
}

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
        }
     }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top