Search code examples
c#asp.netlistpageload

how to keep one List with saved entries after page_load?


i have a list:

public List<string> QuestionIDs;

constructor:

 public EmployeeCategorizationControl()
        {
            QuestionIDs = new List<string>();
        }

lots of radio buttons like this:

<asp:RadioButtonList ID="selectedYesNo1" runat="server" RepeatDirection="Horizontal"
                OnSelectedIndexChanged="FirstQuestionGotAnswered">
                <asp:ListItem Text="Yes" Value="1"></asp:ListItem>
                <asp:ListItem Text="No" Value="0"></asp:ListItem>
            </asp:RadioButtonList>

i am trying to save QuestionID in List here:

protected void FirstQuestionGotAnswered(object sender, EventArgs e)
        {

            QuestionID = selectedYesNo1.Text;
            QuestionIDs.Add(QuestionID);

}

my problem is that after page load when i calling next question based on id of previous, there are no ID in list at all. how schould i save Id for to use them after page_load?


Solution

  • You'll have to put the list in the Viewstate

    public IList<string> QuestionIDs
    {
       get
       {
          var obj = ViewState["QuestionIDs"];
          if(obj == null)
          {
             obj  = new List<string>();
             ViewState["QuestionIDs"] = obj;
          }
          return (IList<string>)obj;
       }
    }