1

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!!

TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
Ahmad Farid
  • 14,398
  • 45
  • 96
  • 136

2 Answers2

1

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

Community
  • 1
  • 1
Colin
  • 10,630
  • 28
  • 36
0
ViewState.Add("key", "value"); //adding value in viewstate 
    String abc = ViewState["key"].ToString(); //getting value from viewstate
Muhammad Akhtar
  • 51,913
  • 37
  • 138
  • 191