System.NullReferenceException: Object reference not set to an instance of an object [duplicate]

萝らか妹 提交于 2020-01-22 03:59:33

问题


Possible Duplicate:
System.NullReferenceException: Object reference not set to an instance of an object

look at my code

if (ViewState["Edit"].ToString() == "new") { 
}
else {
      row = _section.GetBannerEntry(ViewState["Edit"].ToString()); 
}

I was getting the error on this line if (ViewState["Edit"].ToString() == "new") I replaced with if (ViewState["Edit"] != null && ViewState["Edit"].ToString() == "new") it works.

Now I am getting the same error here in else row = _section.GetBannerEntry(ViewState["Edit"].ToString());

please help


回答1:


Your View state is null Check for

if(ViewState["Edit"]!= null)
{
 if (ViewState["Edit"].ToString() == "new")
}



回答2:


If ViewState["Edit"] hasn't been set, .ToString() will throw an exception.

Try one of these:

  • if (ViewState["Edit"]!= null && ViewState["Edit"].ToString() == "new") //best one
  • if (ViewState["Edit"] + "" == "new")



回答3:


Well, either ViewState is null or ViewState["Edit"] is returning null...




回答4:


if (ViewState["Edit"] != null && ViewState["Edit"].ToString() == "new") {

or if whats supposed to be in the viewstate is a string, this should work:

if ((string)ViewState["Edit"] == "new") {



回答5:


Try

protected void btnSaveDetails_Click(object sender, EventArgs e) 
{         
DataRow row = null;          
 if (ViewState["Edit"] != null && ViewState["Edit"].ToString() == "new") 
 {
 }
}


来源:https://stackoverflow.com/questions/6213271/system-nullreferenceexception-object-reference-not-set-to-an-instance-of-an-obj

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