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();
0
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();
}
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.

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.

0

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

3
  • 1
    .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.
    – Mike M.
    Mar 4, 2011 at 19:40
  • 1
    It is already a string and the call to .ToString() is not necessary, but it will not fix your problem.
    – CatDadCode
    Mar 4, 2011 at 19:41
  • 1
    It will solve the null reference exception, because calling .ToString() on a null will throw the exception. Mar 4, 2011 at 19:44
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();
}
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.