0

I need to store some lists into a ViewState.

I created a class:

    [Serializable]
    public class TemplateTypeProcedureListViewState
    {
        public string Name { get; set; }
        public string ProcedureName { get; set; }
        public string ProcedureParameter { get; set; }
        public string ProcedureParameterType { get; set; }
    }

Here is the ViewState:

    private TemplateTypeProcedureListViewState TemplateTypeProcedureList
    {
        get { return (TemplateTypeProcedureListViewState)ViewState["TemplateTypeProcedureList"]; }
        set { ViewState["TemplateTypeProcedureList"] = value; }
    }

I'm giving the values like this:

   var templateTypeProcedureListViewState = new TemplateTypeProcedureListViewState
   {
       Name = ListNameTextBox.Text,
       ProcedureName = ListProcedureNameTextBox.Text,
       ProcedureParameter = ListProcedureParameterTextBox.Text,
       ProcedureParameterType = ListProcedureParameterTypeTextBox.Text
   };                

   ViewState.Add("TemplateTypeProcedureList", templateTypeProcedureListViewState);

Now, when I add another item, the first one is overwritten (or deleted and the other one (second) is saved). Is it possible to save more than one item into a ViewState? Can you refer me something or somewhere? Thanks :)

1
  • add item with different name(key). Commented Oct 16, 2013 at 9:31

1 Answer 1

2

Ok, this happens because you save your new item in Viestate, you do not add an item to list saved in viewstate.

You have do retrieve list first, and only then add item, and of couse save it after.

 var list = TemplateTypeProcedureList.Add(new item);
 TemplateTypeProcedureList = list;

PS: It's not the best way to use viestate, as your page will become larger and larger in size. Try to avoid saving to much info on ViewState.

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

3 Comments

I only need to save these information temporary, because I need to show them in a GridView. But the problem is that I used List<>, and after clicking on a button Add, the information showed in the GridView. BUT, after clicking the button again, the previous information was removed, and only the new information showed. Someone told me use ViewState, so now I'm trying to figure something out. Thanks for help :)
PS. the information that is showed in the GridView, will be cleared after refreshin the page, so no worries about that ;)
Your welcome, it's just an advice, you do not need to absolutely follow it always. If it's helpful don't forget to mark it as an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.