1

When I click on this LinkButton I need to save the object on my list, but if I click again, my list will lost the older value and get list count = 1, any suggestion ?

 List<Product> products = new List<Product>();

 protected void AddProduct_Click(object sender, EventArgs e)
    {
        int productID = Convert.ToInt32((sender as LinkButton).CommandArgument); /*Pega o id do button que foi clicado relativa a reserva*/

        products.Add(ProductBLL.GetProductByID(productID));

        ViewState["products"] = products;
    }
5
  • This is ASP.NET Web Forms? Please remember to tag your question for the appropriate framework in the future. Commented Dec 5, 2018 at 16:29
  • Yes it is. thanks for the advice Commented Dec 5, 2018 at 16:30
  • 1
    You're storing the list in ViewState, but when you next add it, you're using a new List. Don't declare a field (class level variable). Instead, use a local variable, retrieve the list from ViewState (if it exists), and add your item to it. Commented Dec 5, 2018 at 16:30
  • Your products variable very likely does not persist between sessions. As mason suggested, you need to retrieve your list from the ViewState, not start a new list. Commented Dec 5, 2018 at 16:30
  • Thanks guys, you're tips worked! I posted the solution Commented Dec 5, 2018 at 16:38

1 Answer 1

1

I was able to solve the problem by retrieving the list from ViewState if it exists, then adding my item to it.

protected void AddProduct_Click(object sender, EventArgs e)
{
    List<Product> products = new List<Product>();
    if(ViewState["products"] != null)
    products = (List<Product>) ViewState["products"];

    int productID = Convert.ToInt32((sender as LinkButton).CommandArgument); 

    products.Add(ProductBLL.GetProductByID(productID));

    ViewState["products"] = products;
}
Sign up to request clarification or add additional context in comments.

Comments

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.