Question

I am trying to use ViewState to store a collection, but it always get me the error: Object reference not set to an instance of an object. I don't know when to initialize it and where? Sometimes I use:

if(ViewState["X"]==null) ViewState["X"] = new List<Checkitem>();

and I put it at the Page_Init() event, but it keeps initializing it each time to a new instance!!

When I try to write it like:

 if (!IsPostBack)
            ViewState["keywords"] = new List<Checkitem>();

It's not initialized later and shows the error mentioned above!!

Was it helpful?

Solution

ViewState.Add("key", "value"); //adding value in viewstate 
    String abc = ViewState["key"].ToString(); //getting value from viewstate

OTHER TIPS

See this post and my answer to it, I suggest you read up on ASP.NET Page Life Cycle (the image included in the referenced post should provide some clues as where the ViewState is available:

SO POst

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top