Object reference not set to an instance of an object
Asked Answered
M

6

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();
Measurable answered 4/3, 2011 at 19:36 Comment(0)
E
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();
Epifocal answered 4/3, 2011 at 19:40 Comment(0)
G
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();
}
Gaberones answered 4/3, 2011 at 19:40 Comment(0)
C
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.

Cohort answered 4/3, 2011 at 19:39 Comment(0)
M
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.

Muriah answered 4/3, 2011 at 19:38 Comment(0)
D
0

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

Dipper answered 4/3, 2011 at 19:39 Comment(3)
.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.Bernete
It is already a string and the call to .ToString() is not necessary, but it will not fix your problem.Gaberones
It will solve the null reference exception, because calling .ToString() on a null will throw the exception.Dipper
B
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();
}
Boiled answered 18/9, 2013 at 2:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.