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.

1
  • 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"]? Commented Dec 16, 2013 at 10:13

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.