locked
DataTable is not been replaced in Session RRS feed

  • Question

  • User1290073845 posted

    Can someone help me to understand  why session every time gives me same data table?

    Its my final project and i have to submit it on this monday.

    The session must replace every time when linkbutton1 event is called. But Session["db0"] is always having first dataTable which was populated on page load.

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace WebApplication1
    {
        public partial class abc : System.Web.UI.Page
        {
            int glquantity = 1; string glcheckquantity; int newindex=0,oldvalue=0;
            protected void Page_Load(object sender, EventArgs e)
            {
                if(!IsPostBack)
                {
                //string pcat = (Request.QueryString.Get("pcat").ToUpper());
                //brand.InnerHtml = pcat;
                SqlConnection con = new SqlConnection("Data Source=VICKY-PC; Database= estore; Integrated Security=true");
                SqlCommand cmd = new SqlCommand("select * from estore..tblProducts ", con);
                //where pCompany = '" + Request.QueryString.Get("pcat") + "'
                SqlDataAdapter productDA = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                productDA.Fill(dt);
                Repeater1.DataSource = dt;
                Repeater1.DataBind();
                Session["db0"] = dt;
                }

            }

            protected void LinkButton4_Click(object sender, EventArgs e)
            {
                if (((LinkButton)sender).ID != "")
                {

                    string text = ((Label)((LinkButton)sender).FindControl("Label3")).Text;

                    Session["image_id"] = ((LinkButton)sender).ID;
                    Response.Redirect("Single.aspx?ID=" + text);
                }
            }

            protected void LinkButton1_Click(object sender, EventArgs e)
            {
                if (Session["Logininfo"] != null)
                {



                    string text = ((Label)((LinkButton)sender).FindControl("Label3")).Text;
                    int id=int.Parse(text);

                    SqlConnection con = new SqlConnection("Data Source=VICKY-PC; Database= estore; Integrated Security=true");
                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = new SqlCommand("Select isnull(pQuantity,0), * from tblProducts Where pId='" + text + "'", con);
                    DataTable dtStock = new DataTable();
                    da.Fill(dtStock);
                    if (dtStock.Rows.Count > 0)
                    {
                        ViewState["gldt"] = dtStock;
                        glcheckquantity = dtStock.Rows[0]["pQuantity"].ToString();
                    }
                    //naming quntiy as stockcheck
                    DataTable gldt = (DataTable)ViewState["gldt"];
                    int stockcheck = int.Parse(glcheckquantity);
                    DataTable dx = (DataTable)Session["db0"];
                    Session["db"]=dx;
                    Session["db0"] = null;
                    DataTable dcheck = (DataTable)Session["db"];
                    int qtcheckdb = int.Parse(dcheck.Rows[id - 1-20]["pQuantity"].ToString());
                    if (stockcheck > 0 && qtcheckdb >0 )
                    {
                        if (text != null && gldt.Rows.Count > 0)
                        {

                            DataTable dt = (DataTable)Session["productcodecart"];
                            for (int i = 0; i <= (dt.Rows.Count) - 1; i++)
                            {
                                if (dt.Rows[i]["PID"].ToString() == text)
                                {
                                    int update = int.Parse(dt.Rows[i]["Quantity"].ToString());
                                    update += 1;
                                    dt.Rows[i]["Quantity"] = update;
                                    int singleprice = int.Parse(dt.Rows[i]["Price"].ToString());
                                    dt.Rows[i]["Total"] = singleprice * update;
                                    int sessionupdate = (int)Session["Increment"];
                                    sessionupdate += 1;
                                    Session["Increment"] = sessionupdate;
                                    Session["productcodecart"] = dt;
                                    int point1 = int.Parse(text);
                                    int qt1 = int.Parse(dcheck.Rows[point1 - 1-20]["pQuantity"].ToString());
                                    qt1 -= 1;
                                    dcheck.Rows[point1 - 1-20]["pQuantity"] = qt1;
                                    Session["db0"] = dcheck;
                                    
                                    Response.Redirect("index.aspx");;
                                }
                            }
                            int total = int.Parse(gldt.Rows[0]["pPrice"].ToString());
                            total *= glquantity;
                            if (dt == null)
                                dt.Rows.Add(1, text, gldt.Rows[0]["pCompany"].ToString(), gldt.Rows[0]["pPrice"].ToString(), '1', total);
                            else
                                dt.Rows.Add(dt.Rows.Count + 1, text, gldt.Rows[0]["pCompany"].ToString(), gldt.Rows[0]["pPrice"].ToString(), '1', total);
                            Session["productcodecart"] = dt;
                            DataTable db = (DataTable)Session["db"];
                            int point = int.Parse(text);
                            int qt = int.Parse(db.Rows[point - 1-20]["pQuantity"].ToString());
                            qt -= 1;
                            db.Rows[point - 1-20]["pQuantity"] = qt;
                            Session["db0"] = db;
                            
                            oldvalue = (int)Session["Increment"];

                            int index = 1;
                            newindex += index;
                        }

                        Session["increment"] = (newindex + oldvalue);
                        Response.Redirect("index.aspx");
                    }
                    else
                    {

                        string display = "Sorry you cannot buy this product currently it is out of stock";
                        ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + display + "');", true);

                    }
                }
                else
                {
                    //Label2.Text = "You must be logged in to place Order";
                    //Label2.Visible = true;
                    string display = "You have to be logged in to place Order";
                    ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + display + "');", true);
                }


            }

         
        }
    }

    Saturday, August 22, 2015 3:55 PM

Answers

  • User281315223 posted

    Well it looks like as you mentioned, you are initially setting your Session value within your initial page load (e.g. IsPostBack is false) :

    Session["db0"] = dt;

    Then attempting to cast that same Session value as a DataTable, which should work :

    DataTable dx = Session["db0"] as DataTable;

    Then afterwards, you are clearing the Session value out (e.g. setting it to null), performing some logic using the datatable and then setting it to the value dcheck before redirecting :

    Session["db0"] = dcheck;

    Keep in mind that if you are redirecting using Response.Redirect() to the same page you are currently on, this will act as if you are loading the page for the first time and it will go into the original Page_Load event, setting your Session value to dt.

    Have you tried using the debugger to step through the code and checked your various values using the Watch window as it progressed? Doing this might help clear up exactly what is going on in different areas of your code.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, August 22, 2015 4:25 PM
  • User281315223 posted

    You might try explicitly removing the Response.Redirect() calls and see if that fixes the issue. Since you are automatically redirecting to the same page (which would occur on it's own without the redirection), it should maintain your Session value and prevent it from being reset in your !IsPostBack block of your Page_Load method).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 24, 2015 8:17 AM

All replies

  • User281315223 posted

    Well it looks like as you mentioned, you are initially setting your Session value within your initial page load (e.g. IsPostBack is false) :

    Session["db0"] = dt;

    Then attempting to cast that same Session value as a DataTable, which should work :

    DataTable dx = Session["db0"] as DataTable;

    Then afterwards, you are clearing the Session value out (e.g. setting it to null), performing some logic using the datatable and then setting it to the value dcheck before redirecting :

    Session["db0"] = dcheck;

    Keep in mind that if you are redirecting using Response.Redirect() to the same page you are currently on, this will act as if you are loading the page for the first time and it will go into the original Page_Load event, setting your Session value to dt.

    Have you tried using the debugger to step through the code and checked your various values using the Watch window as it progressed? Doing this might help clear up exactly what is going on in different areas of your code.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, August 22, 2015 4:25 PM
  • User1290073845 posted

    Thx Rion William .

    Yes i am redirecting to same page and i have tried it with debugger in the click event when Session["db0"]=dcheck; or Session["db0"]=db; both ------ dcheck and db are updated datatables just their assignment to session["db0"] is not working session remains the same as page loaded datatable. What to do now?

    Saturday, August 22, 2015 5:21 PM
  • User475983607 posted

    This is a common bug that arises when using session to store data that is also stored in a database.  You end up having to write extra code to sync the database and the session tables.  It is far better to grab the data from the database when needed.   The knee jerk reaction to my previous statement is;  Going to the database is a lot of overhead. The truth is storing data in session is far more resource intensive and complicated then letting a database do its job.  

    I realize this is probably not the support you want to hear being you're under a time constraint.  I assure you Session will work just fine to as an intermediate data store.  However, you must devise a plan to update Session every time the database is updated.  This means in the code where you update the database you must also update session. Generally, it would look like an UPDATE followed by a SELECT.  The UPDATE updates the table in the database and the SELECT grabs the latest data (after a successful UPDATE) from the database.  The final step is assigning the data to Session.  Once you start designing with this in mind you'll probably ask yourself; Why am I using Session - it's a bunch of extra work.  

    Still, this does not solve your problem.  What you need to do is follow Rion's advise.  Place a break point and single step through the application paying special attention to the spots where the DB is updated.  Every place where the DB is updated you must also update Session.

    Saturday, August 22, 2015 7:28 PM
  • User1290073845 posted

    Can you provide me a  way to get updated session on after postback because i am creating shopping website whose database data will only be changed when an item is successfully sold i am doing this session["db"] or session["db0"] for maintaining stock so that user adds only no of products as available in  stock and that quantity changes on very product add to cart.

    Sunday, August 23, 2015 1:02 AM
  • User475983607 posted

    Frankly, the code is too complicated.

    You'll really need to use break points and single step through the code and verify the logic flows according to the requirements.  Consider documenting the flow then compare the documented flow to the logic.  This will help identify logical errors.  I would use paper and pencil and draw the expected flow between Session, pages, and the DB.

    Sunday, August 23, 2015 9:52 AM
  • User-1119963761 posted

    Hi 

    try to Reset the session state 

    after passing the data table value from your session 

    try this:  

     Session["db0"] = null;

     

    this will reset your session to the main state .

    Sunday, August 23, 2015 1:36 PM
  • User281315223 posted

    You might try explicitly removing the Response.Redirect() calls and see if that fixes the issue. Since you are automatically redirecting to the same page (which would occur on it's own without the redirection), it should maintain your Session value and prevent it from being reset in your !IsPostBack block of your Page_Load method).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 24, 2015 8:17 AM