2

When I try to open the page from my IDE in VS 2008 using "VIEW IN BROWSER" option I get "Object reference not set to an instance of an object" error.

The piece of code I get this error :

 XResult = Request.QueryString["res"];    
 TextBox1.Text = XResult.ToString();
0

6 Answers 6

6

The problem here is that XResult is null and when you call ToString on it the code produces a NullReferenceException. You need to account for this by doing an explicit null check

TextBox1.Text = XResult == null ? String.empty : XResult.ToString();
Sign up to request clarification or add additional context in comments.

Comments

4

If you are opening the page without the "res" query string then you need to include a check for null before you do anything with it.

if (Request.QueryString["res"] != null)
{
    XResult = Request.QueryString["res"];
    TextBox1.Text = XResult.ToString();
}

Comments

2

That error could be Because the REquest.QueryString method did not find a value for "res" in the url so when you try to do the "toString" to a null object whrow that exeption.

Comments

1

Your code is expecting a query string http://localhost:xxxx/yourapp?res=yourval. It's not present in the address supplied to the browser. In the web section of your project properties, you can supply an appropriate URL. Of course, shoring up your code to allow for this would be advisable.

Comments

0

XResult is already a string, so calling ToString isn't necessary. That should also fix your problem.

3 Comments

.ToString() on a string won't throw an error. The issue is that XResult is null because it's not finding "res" in the query string.
It is already a string and the call to .ToString() is not necessary, but it will not fix your problem.
It will solve the null reference exception, because calling .ToString() on a null will throw the exception.
0

The problem here is that XResult is null, and when you call ToString on it the code produces a NullReferenceException. You need to account for this by doing an explicit null check:

if (Request.QueryString["res"] != null)
{
    XResult = Request.QueryString["res"];
    TextBox1.Text = XResult.ToString();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.