Object reference not set to an instance of an object

大城市里の小女人 提交于 2019-12-11 00:28:24

问题


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

回答1:


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



回答2:


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



回答3:


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.




回答4:


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.




回答5:


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




回答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:

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


来源:https://stackoverflow.com/questions/5198403/object-reference-not-set-to-an-instance-of-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!