storing new record in a new row of datatable while retaining old values

May 23 2010 11:08 AM
I have Desktop.aspx page with Gridview1 and  Detailsview1 controls. My requirement is, if I click on a button in Detailsview1, that particular product name and it's price should be stored in a datatable which is bound to GridView2. So far, I am successful in accomplishing this. However, if I click on another product , a new row is inserted in Datatable, but it shows the first added record and not the recent one. I have stored datatable object in session. My source code is as follows:

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

 

public partial class Desktops : System.Web.UI.Page

{

  

           

    protected void Page_Load(object sender, EventArgs e)

    {

       

        if (!Page.IsPostBack)

        {

            DataTable mydt = new DataTable();

            DataRow myrow;

            mydt.Columns.Add("Product Name");

            mydt.Columns.Add("Price");

            Session["MyDataTable"] = mydt;

        }

    }

   

    protected void DetailsView1_ItemCommand(object sender, DetailsViewCommandEventArgs e)

    {

        

       

        if (e.CommandName == "save")

        {

            ArrayList FavD = (ArrayList)Session["FavDesktops"];

            if (FavD == null)

            {

                FavD = new ArrayList();

            }

            FavD.Add(DetailsView1.Rows[2].Cells[1].Text);

            FavD.Add(DetailsView1.Rows[7].Cells[1].Text);

            Session["FavDesktops"] = FavD;

            DataTable t = (DataTable)Session["MyDataTable"];

            DataRow myrow = t.NewRow();

            myrow = t.NewRow();

 

            myrow["Product Name"] = FavD[0].ToString();

            myrow["Price"] = FavD[1].ToString();

            t.Rows.Add(myrow);

            t.AcceptChanges();

            Session["MyDataTable"] = t;

            GridView2.DataSource = t;

            GridView2.DataBind();

        }

    }

    protected void Page_PreRender(object sender, EventArgs e)

    {

 

        string sFavsHTML = "<p>You are considering the following desktops:</p><p><b>";

        ArrayList alFavorites = (ArrayList)Session["FavDesktops"];

        if (alFavorites != null)

        {

           

           

                foreach (string sItem in alFavorites)

                {

                     sFavsHTML += sItem + "<br />";

                   

                }

           

        }

        else

        {

            sFavsHTML += "None";

        }

        sFavsHTML += "</b></p>";

        lblconsidering.Text = sFavsHTML;

    }

}