Вопрос

Why is this code throwing a NullReferenceException?

Exception:

System.NullReferenceException: Object reference not set to an instance of an object.

Code:

if ((string.IsNullOrEmpty(Request.QueryString["Sno"].ToString())) 
   && (string.IsNullOrEmpty(Request.QueryString["Name"].ToString())))
{
    lblBookedBy.Text = "";
    lblSno.Text = "";
}
else
{
    lblBookedBy.Text = Request.QueryString["Name"].ToString();
    lblSno.Text = Request.QueryString["Sno"].ToString();
}
Это было полезно?

Решение 6

Use Convert.ToString() instead of .ToString() to avoid null reference exception:

if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["Sno"])) && string.IsNullOrEmpty(Covert.ToString(Request.QueryString["Name"])))
{
    lblBookedBy.Text = "";
    lblSno.Text = "";
}
else
{
    lblBookedBy.Text =Convert.ToString(Request.QueryString["Name"]);
    lblSno.Text =Convert.ToString(Request.QueryString["Sno"]);
}

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

I would recommend doing the following.

if (Request.QueryString["Sno"] == null || Request.QueryString["Name"] == null)
{
    lblBookedBy.Text = "";
    lblSno.Text = "";
}
else
{
    lblBookedBy.Text = Request.QueryString["Name"].ToString();
    lblSno.Text = Request.QueryString["Sno"].ToString();
}

You are most likely getting a NullReference in the if statement. This way you are sure not to encounter this, and worst case if both of the variables are instantiated, but one or more contains an empty string it will simply set the Text to empty.

Alternatively if you use Convert.ToString as many other suggested you can simplify the code by skipping the if statement.

lblBookedBy.Text = Convert.ToString(Request.QueryString["Name"]);
lblSno.Text = Convert.ToString(Request.QueryString["Sno"]);

In worst case scenario one of these will be Null, and will result in one of the TextBoxes to show result, while the other one is empty.

Also, assuming that Request.QueryString supports it, you could use TryGetValue.

You are trying to cast Request.QueryString["Sno"] to string while it's value is null

This is most likely because there is no key "Sno" or "Name" in the collection query string which results in the exception when trying to invoke .ToString() on it.

Check if Request.QueryString["Sno"] or Request.QueryString["Name"] is null, before invoking .ToString()

if Request.QueryString["Sno"] or Request.QueryString["Name"] does not return any object than calling ToString will throw exception

Remove .ToString() in null check because when query string parameter is not available you are trying to type cast null variable to string....

if ((string.IsNullOrEmpty(Convert.ToString(Request.QueryString["Sno"]))) && (string.IsNullOrEmpty(Covert.ToString(Request.QueryString["Name"]))))
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top