locked
Can you edit a generic list in viewstate? RRS feed

  • Question

  • User-1072848465 posted

    Can you make changes to a generic list once you save it to viewstate?

    I have no problem adding entries to the list with the following code

      [Serializable]
      public class tableEntry
      {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int personId { get; set; }
        public int ItemsSold { get; set; }
      }
    
    
      public List<tableEntry> Entries
      {
        get
        {
          if (!(ViewState["entryViewState"] is List<tableEntry>))
          {
            ViewState["entryViewState"] = new List<tableEntry>();
          }
    
          return (List<tableEntry>)ViewState["entryViewState"];
        }
      }
    
        protected void addPerson_btn_Click(object sender, EventArgs e)
        {
          
          Entries.Add(new tableEntry
              {
                  FirstName = firstname,
                  LastName = lastname,
                  personId = Convert.ToInt32(selectedPersonId),
                  ItemsSold = Convert.ToInt32(itemsSold_txt.Text)
              }
           );
        }

    I have a Update button on the page that allows the user to edit the items sold amount. When they click updates I want to retrieve Entries and locate the entry by personId and update the Items sold value. This is what I have so far. 

        protected void UpdateOrderBtn_Click(object sender, EventArgs e)
        {      
               int updateItemsSold = 6;
               Entries.First(d => d.ScoutId == scoutId).ItemsSold = updateItemsSold;
        }

    Any assistance would be greatly appreciated.

    Thanks in advance

    Brad

    Tuesday, June 7, 2016 4:50 PM

All replies

  • User765422875 posted

    Yes you can update the value, but you should make the code a bit more robust. As an example:

            int updateItemsSold = 6;
            if (Entries != null)
            {
                tableEntry entry = Entries.First(x => x.personId == 1);
                if (entry != null)
                {
                    entry.ItemsSold = updateItemsSold;
                }
            }

    Tuesday, June 7, 2016 9:07 PM