简体   繁体   中英

Object reference not set to an instance of an object

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();

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();

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

这个错误可能是因为REquest.QueryString方法没有在url中找到“res”的值,所以当你尝试对一个空对象执行“toString”时,该对象执行该操作。

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM