Hi Dave,
Try this follwoing method...
<%@ Page debug=true Language="c#" ContentType="text/html" ResponseEncoding="iso-8859-1" %>
<html>
<head>
<title>Shopping Cart</title>
<script runat="server">
System.Data.DataTable objDT;
System.Data.DataRow objDR;
private void Page_Load(object s, EventArgs e)
{
if (!IsPostBack) {
makeCart();
}
}
public void makeCart()
{
objDT = new System.Data.DataTable("Cart");
objDT.Columns.Add("ID", typeof(int));
objDT.Columns("ID").AutoIncrement = true;
objDT.Columns("ID").AutoIncrementSeed = 1;
objDT.Columns.Add("Quantity", typeof(int));
objDT.Columns.Add("Product", typeof(string));
objDT.Columns.Add("Cost", typeof(decimal));
Session("Cart") = objDT;
}
public void AddToCart(object s, EventArgs e)
{
objDT = Session("Cart");
object Product = ddlProducts.SelectedItem.Text;
bool blnMatch = false;
foreach ( objDR in objDT.Rows)
{
if (objDR("Product") == Product)
{
objDR("Quantity") += txtQuantity.Text;
blnMatch = true;
break; // TODO: might not be correct. Was : Exit For
}
}
if (!blnMatch)
{
objDR = objDT.NewRow;
objDR("Quantity") = txtQuantity.Text;
objDR("Product") = ddlProducts.SelectedItem.Text;
objDR("Cost") = decimal.Parse(ddlProducts.SelectedItem.Value);
objDT.Rows.Add(objDR);
}
Session("Cart") = objDT;
dg.DataSource = objDT;
dg.DataBind();
lblTotal.Text = "$" + GetItemTotal();
}
public decimal GetItemTotal()
{
int intCounter;
decimal decRunningTotal;
for (intCounter = 0; intCounter <= objDT.Rows.Count - 1; intCounter++)
{
objDR = objDT.Rows(intCounter);
decRunningTotal += (objDR("Cost") * objDR("Quantity"));
}
return decRunningTotal;
}
public void Delete_Item(object s, DataGridCommandEventArgs e)
{
objDT = Session("Cart");
objDT.Rows(e.Item.ItemIndex).Delete();
Session("Cart") = objDT;
dg.DataSource = objDT;
dg.DataBind();
lblTotal.Text = "$" + GetItemTotal();
}
</script>
</head>
<body>
<form runat="server">
Product:<br>
<asp:DropDownList id=ddlProducts runat="server">
<asp:ListItem Value="4.99">Socks</asp:ListItem>
<asp:ListItem Value="34.99">Pants</asp:ListItem>
<asp:ListItem Value="14.99">Shirt</asp:ListItem>
<asp:ListItem Value="12.99">Hat</asp:ListItem>
</asp:DropDownList><br>
Quantity:<br>
<asp:textbox id="txtQuantity" runat="server" /><br><br>
<asp:Button id=btnAdd runat="server" Text="Add To Cart" onClick="AddToCart" /><br><br>
<asp:DataGrid id=dg runat="server" ondeletecommand="Delete_Item">
<columns>
<asp:buttoncolumn buttontype="LinkButton" commandname="Delete" text="Remove Item" />
</columns>
</asp:DataGrid>
<br><br>
Total:
<asp:Label id=lblTotal runat="server" />
</form>
</body>
</html>
Good Luck
Regards
Hari K......
Enter your message below
Sign in or Join us (it's free).