JNeves
JNeves

Reputation: 41

Save values in list after click event

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;
    }

Upvotes: 1

Views: 888

Answers (1)

JNeves
JNeves

Reputation: 41

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;
}

Upvotes: 1

Related Questions