Hi there,
I have a basic shopping cart which i have written in asp.net which uses SQL server 2000. Everything is working well apart from one small thing, each time i add an item to my basket, the page jumps back to page 1, so if i add an item on page 3, as soon as the item is added it jumps back to page 1. I have a Response.AppendHeader("Refresh", "0"); to update the pages item count & total, i think this has something to do with the rebinding of the dataList.
My full code:
public partial class content : System.Web.UI.Page
{
const int RECORDS_PER_PAGE = 8;
int totalRecords;
DataSet products = new DataSet();
DataTable objCartDT = new DataTable();
DataRow objDR;
int item_Count;
decimal totalPrice;
SqlConnection connection = new
SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand command;
protected void Page_Load(object sender, EventArgs e)
{
//Check shopping cart and create if it exists
objCartDT = (DataTable)Session["Cart"];
if (objCartDT == null)
{
objCartDT = new DataTable("Cart");
objCartDT.Columns.Add("CartID", typeof(Int32));
objCartDT.Columns["CartID"].AutoIncrement = true;
objCartDT.Columns["CartID"].AutoIncrementSeed = 1;
objCartDT.Columns.Add("ItemID", typeof(String));
objCartDT.Columns.Add("Quantity", typeof(Int32));
objCartDT.Columns.Add("Name", typeof(String));
objCartDT.Columns.Add("Price", typeof(String));
Session["Cart"] = objCartDT;
}
// display items in cart
lbl_Items_in_cart.Text = GetItemQuantity();
lbl_total.Text = GetTotalPrice();
// get the number of records found in the database
totalRecords = GetProductsCount();
// calculate and save the number of
// pages to the Pages hidden field
Pages.Value = Math.Ceiling((double)totalRecords / RECORDS_PER_PAGE).ToString();
if (!Page.IsPostBack)
{
//Bind records to DataList on page load
BindData();
}
}
protected void BindData()
{
int pageNumber = int.Parse(PageNumber.Value);
int totalPages = int.Parse(Pages.Value);
string CD_Category = Request.QueryString["ddl"];
string searchCriteria = Request.QueryString["s"];
if (searchCriteria != "View all")
{
command = new SqlCommand("Display_Selected_CDs", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@dotnet.itags.org.PageNumber", pageNumber);
command.Parameters.Add("@dotnet.itags.org.PageSize", RECORDS_PER_PAGE);
command.Parameters.Add("@dotnet.itags.org.CD_Selected", searchCriteria);
command.Parameters.Add("@dotnet.itags.org.CD_Category", CD_Category);
}
else
{
command = new SqlCommand("Display_All_CDs", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@dotnet.itags.org.PageNumber", pageNumber);
command.Parameters.Add("@dotnet.itags.org.PageSize", RECORDS_PER_PAGE);
}
connection.Open();
products = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
adapter.Fill(products, "CDs");
connection.Close();
// Bind Data to the DataList
DL_CD_List.DataSource = products;
DL_CD_List.DataBind();
// enable/disable the links to navigate through the pages
FirstPage.Enabled = (pageNumber != 1);
FirstPage.Visible = (pageNumber != 1);
PrevPage.Enabled = (pageNumber != 1);
PrevPage.Visible = (pageNumber != 1);
NextPage.Enabled = (pageNumber != totalPages);
NextPage.Visible = (pageNumber != totalPages);
LastPage.Enabled = (pageNumber != totalPages);
LastPage.Visible = (pageNumber != totalPages);
// display number of pages found, current page number
Info.Text = totalRecords + " CD's found | Page " + PageNumber.Value + " of "
+ Pages.Value + "<br><br>";
}
// return the number of total records in database
protected int GetProductsCount()
{
SqlConnection connection = new
SqlConnection(ConfigurationManager.ConnectionStrings["webDBmultitraxConnectionString"].ConnectionString);
SqlCommand command;
if( Request.QueryString["s"] != "View all")
{
command = new SqlCommand("SELECT Count(*) FROM CD_Titles_Info WHERE " + Request.QueryString["ddl"] + "= '" + Request.QueryString["s"] + "'", connection);
}
else
{
command = new SqlCommand("SELECT Count(*) FROM CD_Titles_Info", connection);
}
if (Request.QueryString["ddl"] == "CD_name")
{
command = new SqlCommand("SELECT Count(*) FROM CD_Titles_Info WHERE CD_name LIKE '" + Request.QueryString["s"] + "'", connection);
}
connection.Open();
int count = (int)command.ExecuteScalar();
connection.Close();
return count;
}
// execute when user clicks on the next/prev/first/last button
protected void Page_Changed(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "FirstPage":
PageNumber.Value = "1";
break;
case "PrevPage":
PageNumber.Value = (int.Parse(PageNumber.Value) - 1).ToString();
break;
case "NextPage":
PageNumber.Value = (int.Parse(PageNumber.Value) + 1).ToString();
break;
case "LastPage":
PageNumber.Value = Pages.Value;
break;
}
// rebind data
BindData();
}
// goto details page and pass CD_ID
protected void display_Details(object sender, CommandEventArgs e)
{
Response.Write(e.CommandName);
}
DataSet FindItem(string CD_ID)
{
DataSet objCDInfo = new DataSet();
SqlDataAdapter CD_DA = new SqlDataAdapter("SELECT * FROM CD_TITLES_INFO WHERE CD_ID = '" + CD_ID + "'", connection);
CD_DA.Fill(objCDInfo, "CD_Info");
return objCDInfo;
}
string GetItemQuantity()
{
item_Count = 0;
foreach (DataRow objDR in objCartDT.Rows)
{
item_Count += Convert.ToInt32(objDR["Quantity"]);
}
string total_item_count = item_Count.ToString();
return total_item_count;
}
string GetTotalPrice()
{
totalPrice = 0;
foreach (DataRow objDR in objCartDT.Rows)
{
totalPrice += Convert.ToInt32(objDR["Quantity"]) * Convert.ToDecimal(objDR["Price"]);
}
string total_price_count = totalPrice.ToString();
Session["currentTotal"] = total_price_count;
return total_price_count;
}
protected void btn_Checkout_Click(object sender, EventArgs e)
{
Response.Redirect("checkout.aspx");
}
protected void DL_CD_List_SelectedIndexChanged(object sender, EventArgs e)
{
lbl_Items_in_cart.Text = GetItemQuantity();
lbl_total.Text = GetTotalPrice();
}
protected void add_CD_to_Cart(object sender, CommandEventArgs e)
{
try
{
//string itemID = e.CommandName;
string itemID = e.CommandName.ToString();
DataSet objCDInfo = FindItem(itemID);
//check if item exists already in the cart
bool blnMatch = false;
foreach (DataRow objDR in objCartDT.Rows)
{
if (objDR["ItemID"].ToString() == itemID)
{
int Quantity = Convert.ToInt32(objDR["Quantity"]);
Quantity += 1;
objDR["Quantity"] = Quantity;
blnMatch = true;
break;
}
}
if (!blnMatch)
{
objDR = objCartDT.NewRow();
objDR["ItemID"] = itemID;
objDR["Quantity"] = 1;
objDR["Name"] = objCDInfo.Tables["CD_Info"].Rows[0]["CD_name"];
objDR["Price"] = objCDInfo.Tables["CD_Info"].Rows[0]["CD_Price"];
objCartDT.Rows.Add(objDR);
}
Response.AppendHeader("Refresh", "0");
}
catch (Exception objException)
{
Response.Write(objException.StackTrace);
}
}
}
I have played around with the cde but i can't find a solution. If i remove the Response.AppendHeader("Refresh", "0"); then the item count & total price only update when the user clicks the next/prev page. I guess this is because the page is reloaded and then the fields update.
Any pointers grately appreciated. Thanks.I figured it out, it's always those silly bugs that take ages to solve or maybe its my bad programming.
The solution was simple, by adding the following to the Add_CD_to_cart method:
lbl_Items_in_cart.Text = GetItemQuantity();
lbl_total.Text = GetTotalPrice();
and removing...
Response.AppendHeader("Refresh", "0");
Thanks.
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment