ViewState询问对象的实例

时间:2013-12-16 10:12:38

标签: c# asp.net

我正在尝试使用代码中的viewdate,如下所示,我收到下面的错误消息,任何想法为什么会发生这种情况。

正在使用的代码

var state = ViewState["GridViewIndex"].ToSting()

错误消息

对象引用未设置为对象的实例。

3 个答案:

答案 0 :(得分:1)

使用

var state = Convert.ToString(ViewState["GridViewIndex"]);

而不是ToString()

ViewState["GridViewIndex"]为null并且只返回null或string.Empty时,这不会崩溃。

答案 1 :(得分:0)

您收到该错误的原因是因为ViewState [“GridViewIndex”]不是对象的实例。

ViewState就像一个dicionary,但是对于给定的键,如果没有实例化对象,则可能会得到一个空引用。请更改您的代码以检查空引用,因为将其转换为字符串。

这样的东西
string state = string.Empty;
if(ViewState["GridViewIndex"] != null)
{
   state = ViewState["GridViewIndex"].ToString();
}

或者也可能使用Convert.ToString代替ToString,如RononDex告诉我们的那样,但一般来说我们需要检查空引用。

答案 2 :(得分:0)

ViewState["GridViewIndex"] = 'get the value
var state = string.empty;
if(ViewState["GridViewIndex"] != null)
{
   state = ViewState["GridViewIndex"].ToString();
}

由于您尚未为 ViewState [“GridViewIndex”] 指定任何值,因此会抛出错误对象引用未设置为对象的实例。 所以首先分配一个值,然后将其传递给变量状态。

希望这有帮助

快乐编码