Question

I need to add the itemid from the list of rows when I click 'add to cart' button in the gridview, I was able to pass this itemid to a arraylist.

But the problem is that everytime I click the button the previous itemid is overwritten with the new item instead I want the arraylist to expand.

public partial class Drama_k : System.Web.UI.Page
{
    string Cn=@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ewap_k.mdf;Integrated Security=True;User Instance=True";
    ArrayList arrValues = new ArrayList(4);

protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName=="AddToCart")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            Session["item"] = GridView2.DataKeys[index].Value.ToString();
            arrValues.Add(Session["item"]);
            GridView1.DataSource = arrValues;
            GridView1.DataBind();
        }
    }
}
Was it helpful?

Solution

don't forget that the arraylist is not stored somewhere, you have to store it in the user's session and on each postback caused by the button retrieve it from the session and add the item clicked by the user.

Edit: Here is a little sample of how you should store the ArrayList in the session and retrieve it on each postback.

    public partial class _Default : System.Web.UI.Page
{
    ArrayList array;
    protected void Page_Load(object sender, EventArgs e)
    {
        if(Session["array"] == null)
        {
            array = new ArrayList();
            Session.Add("array", array);
        }
        else
            array = Session["array"] as ArrayList;
        GridView1.DataSource = array; 
        GridView1.DataBind(); //Edit 2
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        array.Add(DateTime.Now);
    }
}

if you still have questions let me know.

OTHER TIPS

You just need to store that ArrayList in the ViewState or Session so it will retain its values between postbacks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top