C# .NET - how to sum items in a prepopulated listbox in asp.net and c#??

Asked By soma on 30-Dec-10 08:36 PM
I have a shopping cart that shows the list of items purchased like

   2 pencil @ $2.00 total $4.00

   1pen @ $3.00 total $3.00

   I want the total to be shown in a seperate text box below the listbox(shopping cart) as $7.00

   how to do it? help needed...
Venkat K replied to soma on 30-Dec-10 10:06 PM
What control you are using to show your cart items? Datagrid, Datalist, any table etc... .Based on the control you used we need to iterate through the items.

Or you can also loop through the datatable or array where the cart items exist.

Thanks
soma replied to Venkat K on 30-Dec-10 11:02 PM
I am creating a shopping cart project with the data source to be a XML file and when i click show shopping cart it will show all the items selected and the total below......

Something to do with sessions
//This is the utility code where i create xml file of items and prices 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Xml.Serialization;
  
/// <summary>
/// Summary description for PizzaUtilities
/// </summary>
public class PizzaUtilities
{
  public static void CreateDefaultPriceList()
  {
  
    String PriceList = System.Web.Configuration.WebConfigurationManager.AppSettings["PriceList"];
    String PriceListLocal = HttpContext.Current.Server.MapPath(PriceList);
    if (!System.IO.File.Exists(PriceListLocal))
    {
      List<Pizza> lstpizza = new List<Pizza>();
      lstpizza.Add(new Pizza() { KindOfPizza = "Combo", SizeOfPizza = "Large", Price = (decimal)29.99 });
      lstpizza.Add(new Pizza() { KindOfPizza = "Chicken", SizeOfPizza = "Large", Price = (decimal)24.99 });
      lstpizza.Add(new Pizza() { KindOfPizza = "Vegi", SizeOfPizza = "Large", Price = (decimal)19.99 });
      lstpizza.Add(new Pizza() { KindOfPizza = "Combo", SizeOfPizza = "Medium", Price = (decimal)24.99 });
      lstpizza.Add(new Pizza() { KindOfPizza = "Chicken", SizeOfPizza = "Medium", Price = (decimal)19.99 });
      lstpizza.Add(new Pizza() { KindOfPizza = "Vegi", SizeOfPizza = "Medium", Price = (decimal)14.99 });
      lstpizza.Add(new Pizza() { KindOfPizza = "Combo", SizeOfPizza = "Small", Price = (decimal)19.99 });
      lstpizza.Add(new Pizza() { KindOfPizza = "Chicken", SizeOfPizza = "Small", Price = (decimal)14.99 });
      lstpizza.Add(new Pizza() { KindOfPizza = "Vegi", SizeOfPizza = "Small", Price = (decimal)9.99 });
  
      using (System.IO.FileStream fs = new System.IO.FileStream(PriceListLocal, System.IO.FileMode.Create))
      {
        System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(lstpizza.GetType());
        xs.Serialize(fs, lstpizza);
        fs.Flush();
        fs.Close();
  
      }
    }
  }
  
  public static List<Pizza> GetPriceList()
  {
    string PriceList = System.Web.Configuration.WebConfigurationManager.AppSettings["PriceList"];
    string PriceListLocal = HttpContext.Current.Server.MapPath(PriceList);
    if (!File.Exists(PriceListLocal))
      CreateDefaultPriceList();
    using (FileStream fs = new FileStream(PriceListLocal, FileMode.Open, FileAccess.Read))
    {
      XmlSerializer xs = new XmlSerializer(typeof(List<Pizza>));
      List<Pizza> pricelist = xs.Deserialize(fs) as List<Pizza>;
      fs.Close();
      return pricelist;
    }
  
  }
  public static List<ShoppingCartItem> ShoppingCart
  {
    get
    {
      List<ShoppingCartItem> items = HttpContext.Current.Session["ShoppingCart"] as List<ShoppingCartItem>;
      if (items == null)
      {
        items = new List<ShoppingCartItem>();
        HttpContext.Current.Session["ShoppingCart"] = items;
      }
      return items;
    }
  }
}
  
// code for shoppingcartitem where i calculate price
  
sing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
  
/// <summary>
/// Summary description for ShoppingCartItem
/// </summary>
public class ShoppingCartItem
{
  
  public Pizza Pizza{ get; set; }
  //public string SizeOfPizza { get; set; }
  public int Quantity { get; set; }
  public string ExtraChesse { get; set; }
  
  
  public string ItemDesc
  {
    get 
    {
      return ToString();
    }
  }
  public override string ToString()
  {
    string item = "";
    if(ExtraCheese)
      return item = string.Format("{0}[Extra Cheese] {1} {2} @ {3} each Subtotal {4:c}", Quantity, Pizza.SizeOfPizza, Pizza.KindOfPizza, Pizza.Price, (Pizza.Price+1.99M) * Quantity);
    else
    return string.Format("{0} {1} {2} @ {3} each SubTotal {4:c}", Quantity,Pizza.SizeOfPizza,Pizza.KindOfPizza,Pizza.Price,Pizza.Price*Quantity );
  }
  
  public bool ExtraCheese { get; set; }
soma replied to Venkat K on 30-Dec-10 11:04 PM
There is an orders page where the order is placed.

and also in the shopping cart when i delete the items it gets deleted but when i go to the home and go again t the shopping cart it shows me the deleted items.

can i know what to do for that too.???

thank you
Rohan Dave replied to soma on 30-Dec-10 11:06 PM
hey Sonam - your code looks like below. I have written code on button Click event to show it on textbox..

double dTotal=0;

foreach (ListItem objLI in ListBox1.Items)

{

  if (objLI.Selected)

  {

    string strPrice = objLI.Text.Substring(objLI.Text.LastIndexOf("$") + 1, objLI.Text.Length - objLI.Text.LastIndexOf("$")-1);

    dTotal += Convert.ToDouble(strPrice);

  }

}

What i have done here is , i have get the total value from the content of listbox with the help of Substring( ) function. First i have find the Position of last "$" sign and determine from where i need to extract the amount from the content. Then sum it up into the double variable..

that's all.. try by it and let me know...

soma replied to Rohan Dave on 30-Dec-10 11:35 PM
the list box doesn't show the total , it shows the value of each product added to cart.

like 1 pencil @$1.00 total $1.00

    2 pens @$2.00 total $ 4.00

    the net total will be $5.00

      I want this net total to be displayed in the textbox
Rohan Dave replied to soma on 30-Dec-10 11:37 PM
yes i know that and that's what the code i sent you, is doing.. have your tried the code to execute ?
soma replied to Rohan Dave on 30-Dec-10 11:41 PM
yes I have tried it but it is not working
Rohan Dave replied to soma on 30-Dec-10 11:56 PM
it should have to work. see the below code and screen shot of result..

double dTotal=0;

foreach (ListItem objLI in ListBox1.Items)

{

if (objLI.Selected)

{

string strPrice = objLI.Text.Substring(objLI.Text.LastIndexOf("$") + 1, objLI.Text.Length - objLI.Text.LastIndexOf("$")-1);

dTotal += Convert.ToDouble(strPrice);

}

}

TextBox4.Text = dTotal.ToString();

see the screen shot of result :


soma replied to Rohan Dave on 30-Dec-10 11:58 PM
http://PizzaCorner.zip

I have attached my project
Rohan Dave replied to soma on 31-Dec-10 12:02 AM
okay.. i will look into it. once i will find solution i will let you know...

my email id => rohan.dave7784@gmail.com
soma replied to Rohan Dave on 31-Dec-10 12:09 AM
i get 0 when i click the button
Rohan Dave replied to soma on 31-Dec-10 12:19 AM
wait i am looking into it good frnd..
soma replied to Rohan Dave on 31-Dec-10 12:24 AM

thank you and I also want help in deleting items from cart......

Will you reply after u found the soln here or do i need to mail you to your personal id??

Rohan Dave replied to soma on 31-Dec-10 12:32 AM
no need for thanks..

both is fine with me email or put the solution here..

i have run your application. I am confused when at which time you want to show total in texbox under your Listbox in Showcart.aspx page ? I mean once you select your Order and click on ADD TO CART , at that time do you want to show total in textbox of Showcart.aspx page ?

let me know quick...
Vivek Jagga replied to soma on 31-Dec-10 12:38 AM
Soma,

On rowdatabound event of your datacontrol, find the control where total amount is display for a particular row and save this in a variable and iterate your datacontrol till datacontrol had rows. At last you have a variable in which grand total shown and you can use it any where after your datacontrol.
soma replied to Vivek Jagga on 31-Dec-10 02:17 AM

rohan, yes I want the total to be displayed in the showcart page. after I click add to cart button...


 the code works but only when i select an item in list box it gives the total and that too only partial value...

soma replied to Rohan Dave on 31-Dec-10 02:28 AM

rohan, yes I want the total to be displayed in the showcart page. after I click add to cart button...


 the code works but only when i select an item in list box it gives the total and that too only partial value...

Sorry for the late reply......

Rohan Dave replied to soma on 31-Dec-10 03:11 AM
no need for sorry...I have modified the code. Give me your email id, so that i will send you the updated cs file code of Showcart page..
Rohan Dave replied to Rohan Dave on 31-Dec-10 05:26 AM
see the below modified code. I have made one method to bind the ListBox with Cart items. And also i have modified the code for Remove and Clear items from ListBox..

private double dTotal = 0;

private double dSubTotal = 0;

private string strItemPrice = "";

private string strRemoveItemPrice = "";

protected void Page_Load(object sender, EventArgs e)

{

  if (!IsPostBack)

  {

    //BindListBox() method will bind the listbox with cart items.

    this.BindListBox();

    //code to show total in textbox

    foreach (ListItem objLI in lstShowcart.Items)

    {

      strItemPrice = objLI.Text.Substring(objLI.Text.LastIndexOf("$") + 1, objLI.Text.Length - objLI.Text.LastIndexOf("$") - 1);

      dTotal += Convert.ToDouble(strItemPrice);

    }

    txtTotp.Text = string.Format("{0:c}", dTotal);

  }

  ViewState["TotalPayment"] = txtTotp.Text;

}

protected void btnRemove_Click(object sender, EventArgs e)

{

  if (lstShowcart.Items.Count > 0)

  {

    //as we remove selected item from ListBox, we also need to update the total payment by substracting price of selected item from total payment.

    strRemoveItemPrice = lstShowcart.SelectedItem.Text.Substring(lstShowcart.SelectedItem.Text.LastIndexOf("$") + 1, lstShowcart.SelectedItem.Text.Length - lstShowcart.SelectedItem.Text.LastIndexOf("$") - 1);

    dSubTotal = Convert.ToDouble(ViewState["TotalPayment"].ToString().Substring(1, ViewState["TotalPayment"].ToString().Length - 1)) - Convert.ToDouble(strRemoveItemPrice);

    /*

      You need to remove the item from your List<ShoppingCartItem> ShoppingCart collection itself not from the ListBox Items collection.

      If we remove the item from ListBox Items collection then it will appear again once we add new order from Order page as the item exist in List<ShoppingCartItem> ShoppingCart.

    */

    PizzaUtilities.ShoppingCart.RemoveAt(lstShowcart.SelectedIndex);

    //after removing item, bind the updated ShoppingCart collection to ListBox again

    this.BindListBox();

    txtTotp.Text = string.Format("{0:c}", dSubTotal);

  }

  ViewState["TotalPayment"] = txtTotp.Text;

  #region your Old Code

  //lstShowcart.Items.Remove(lstShowcart.SelectedItem);

  /* for (int i = 0; i < lstShowcart.Items.Count; i++)

  {


    lstShowcart.Items.RemoveAt(lstShowcart.SelectedIndex);


  }
  */

  #endregion

}

protected void btnClr_Click(object sender, EventArgs e)

{

  /*

    Again if Click on Clear, then we need to clear the List<ShoppingCartItem> ShoppingCart collection not the ListBox Items collection.

    once we will clear/remove items from ShoppingCart collection, ListBox automatically clear the items

  */

  if (lstShowcart.Items.Count > 0)

  {

    PizzaUtilities.ShoppingCart.RemoveRange(0, lstShowcart.Items.Count);

    this.BindListBox();

  }

  txtTotp.Text = "$0.00";

  ViewState["TotalPayment"] = txtTotp.Text;

  #region your Old Code

  //lstShowcart.Items.Clear();

  //lstShowcart.ClearSelection;

  #endregion

}

/// <summary>

/// BindListBox() method will bind the items to list box from ShoppingCart. I have created the separate method as we need to bind listbox

/// again once we remove the item from Cart

/// </summary>

private void BindListBox()

{

  lstShowcart.DataSource = PizzaUtilities.ShoppingCart;

  lstShowcart.DataTextField = "ItemDesc";

  lstShowcart.DataBind();

}

I have tired it and it;s working fine.. See the below screen shot also :

Rohan Dave replied to Rohan Dave on 31-Dec-10 05:38 AM
see the below modified code. I have made one method to bind the ListBox with Cart items. And also i have modified the code for Remove and Clear items from ListBox..

private double dTotal = 0;

private double dSubTotal = 0;

private string strItemPrice = "";

private string strRemoveItemPrice = "";

protected void Page_Load(object sender, EventArgs e)

{

  if (!IsPostBack)

  {

  //BindListBox() method will bind the listbox with cart items.







  this.BindListBox();

  //code to show total in textbox


  foreach (ListItem objLI in lstShowcart.Items)

  {

    strItemPrice = objLI.Text.Substring(objLI.Text.LastIndexOf("$") + 1, objLI.Text.Length - objLI.Text.LastIndexOf("$") - 1);

    dTotal += Convert.ToDouble(strItemPrice);

  }

  txtTotp.Text = string.Format("{0:c}", dTotal);

  }

  ViewState["TotalPayment"] = txtTotp.Text;

}

protected void btnRemove_Click(object sender, EventArgs e)

{

  if (lstShowcart.Items.Count > 0)

  {

  //as we remove selected item from ListBox, we also need to update the total payment by substracting price of selected item from total payment.

  strRemoveItemPrice = lstShowcart.SelectedItem.Text.Substring(lstShowcart.SelectedItem.Text.LastIndexOf("$") + 1, lstShowcart.SelectedItem.Text.Length - lstShowcart.SelectedItem.Text.LastIndexOf("$") - 1);

  dSubTotal = Convert.ToDouble(ViewState["TotalPayment"].ToString().Substring(1, ViewState["TotalPayment"].ToString().Length - 1)) - Convert.ToDouble(strRemoveItemPrice);

  /*

    You need to remove the item from your List<ShoppingCartItem> ShoppingCart collection itself not from the ListBox Items collection.

    If we remove the item from ListBox Items collection then it will appear again once we add new order from Order page as the item exist in List<ShoppingCartItem> ShoppingCart.

  */

  PizzaUtilities.ShoppingCart.RemoveAt(lstShowcart.SelectedIndex);

  //after removing item, bind the updated ShoppingCart collection to ListBox again

  this.BindListBox();

  txtTotp.Text = string.Format("{0:c}", dSubTotal);

  }

  ViewState["TotalPayment"] = txtTotp.Text;

  #region your Old Code

  //lstShowcart.Items.Remove(lstShowcart.SelectedItem);

  /* for (int i = 0; i < lstShowcart.Items.Count; i++)

  {


  lstShowcart.Items.RemoveAt(lstShowcart.SelectedIndex);


  }
  */

  #endregion

}

protected void btnClr_Click(object sender, EventArgs e)

{

  /*

  Again if Click on Clear, then we need to clear the List<ShoppingCartItem> ShoppingCart collection not the ListBox Items collection.

  once we will clear/remove items from ShoppingCart collection, ListBox automatically clear the items

  */

  if (lstShowcart.Items.Count > 0)

  {

  PizzaUtilities.ShoppingCart.RemoveRange(0, lstShowcart.Items.Count);

  this.BindListBox();

  }

  txtTotp.Text = "$0.00";

  ViewState["TotalPayment"] = txtTotp.Text;

  #region your Old Code

  //lstShowcart.Items.Clear();

  //lstShowcart.ClearSelection;

  #endregion

}

/// <summary>

/// BindListBox() method will bind the items to list box from ShoppingCart. I have created the separate method as we need to bind listbox

/// again once we remove the item from Cart

/// </summary>

private void BindListBox()

{

  lstShowcart.DataSource = PizzaUtilities.ShoppingCart;

  lstShowcart.DataTextField = "ItemDesc";

  lstShowcart.DataBind();

}

I have tired it and it;s working fine.. See the below screen shot also :