【问题标题】:ViewState asking for instance of object [duplicate]ViewState 询问对象的实例 [重复]
【发布时间】:2014-01-03 16:26:16
【问题描述】:

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

正在使用的代码

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

错误信息

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

【问题讨论】:

  • 这段代码在哪里使用?在页面生命周期的哪个阶段?并且实际上将值设置为 into ViewState["GridViewIndex"]?

标签: c# asp.net


【解决方案1】:
ViewState["GridViewIndex"] = 'get the value
var state = string.empty;
if(ViewState["GridViewIndex"] != null)
{
   state = ViewState["GridViewIndex"].ToString();
}

由于您没有为 ViewState["GridViewIndex"] 分配任何值,它会引发错误 Object reference not set to an object of an instance. 所以首先分配一个值,然后将其传递给变量 state。

希望对你有帮助

快乐编码

【讨论】:

    【解决方案2】:

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

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

    类似

    string state = string.Empty;
    if(ViewState["GridViewIndex"] != null)
    {
       state = ViewState["GridViewIndex"].ToString();
    }
    

    或者也可以像 RononDex 告诉我们的那样使用 Convert.ToString 而不是 ToString,但通常我们需要检查空引用。

    【讨论】:

      【解决方案3】:

      使用

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

      而不是ToString()

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

      【讨论】:

        猜你喜欢
        • 2011-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-27
        • 2018-06-13
        相关资源
        最近更新 更多