0

I am trying to a viewdate in code as can be seen below and i am getting the error message below, any ideas why this would be happening.

Code being used

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

Error Message

Object reference not set to an instance of an object.

user3086751
  • 197
  • 2
  • 16
  • 2
    Where is this code being used? At what point in the page life-cycle? And had a value actually be set *into* ViewState["GridViewIndex"]? – freefaller Dec 16 '13 at 10:13

3 Answers3

1

Use

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

instead of ToString()

This won't crash when ViewState["GridViewIndex"] is null and just return null or string.Empty.

RononDex
  • 3,876
  • 19
  • 35
0

The reason why you're getting that error is because ViewState["GridViewIndex"] is not an instance of an object.

ViewState is like a dicionary, but for a given key you might get a null reference, if no object is instantiated. Please change your code to check for null references because convert it to string.

Something like

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

or might also use Convert.ToString instead of ToString as RononDex told us, but in general we need to check for null references.

Bruno Costa
  • 2,558
  • 2
  • 15
  • 24
0
ViewState["GridViewIndex"] = 'get the value
var state = string.empty;
if(ViewState["GridViewIndex"] != null)
{
   state = ViewState["GridViewIndex"].ToString();
}

Since you haven't assigned any values to the ViewState["GridViewIndex"] it throws an error Object reference not set to an instance of an object. so first assign a value then pass it to the variable state.

Hope this helps

Happy Coding

Amarnath Balasubramanian
  • 8,498
  • 7
  • 30
  • 59