I have a shopping cart page where if an item is Real Estate Forms 2d then there will be a sales tax assessed. If it equals any other item there will be no sales tax assessed. The problem I am having is I can't get a sales tax assessed for any of the item with my current code. Can someone provide assistance in what I am doing wrong with the code below and what I can do to correct it. This is just part of my code:

bool blnNoCart = false; 
// get the user's cart 
if (Session["CartID"] != null) 
{ 
ShoppingCart objCart = ShoppingCart.Resume(Convert.ToInt32(Session["CartID"])); 
if (objCart == null || objCart.Count == 0) 
{ 
blnNoCart = true; 
} 
else 
{ 
foreach (ShoppingCartItem item in objCart.GetItem()) 
{ 
if (item.Name == "Real Estate Forms 2d") 
{ 
objCart.TaxRate = 0.06; 
} 
objCart.TaxRate = 0.00; 
} 

double dblShipping = 6;
Comments
duplicate posts

Try changing this:

if (item.Name == "Real Estate Forms 2d")
 {
 objCart.TaxRate = 0.06;
 }
 objCart.TaxRate = 0.00;

to this:

if (item.Name == "Real Estate Forms 2d")
 {
 objCart.TaxRate = 0.06;
 }
else
{
 objCart.TaxRate = 0.00;
 }

Without the else, you are setting the taxrate to 0.06 inside the for statement, then setting it to 0.00 on the next line :)

Remember to mark the thread as solved if this fixes your problem

Edited 7 Years Ago by Geekitygeek: n/a

Try changing this:

if (item.Name == "Real Estate Forms 2d")
 {
 objCart.TaxRate = 0.06;
 }
 objCart.TaxRate = 0.00;

to this:

if (item.Name == "Real Estate Forms 2d")
 {
 objCart.TaxRate = 0.06;
 }
else
{
 objCart.TaxRate = 0.00;
 }

Without the else, you are setting the taxrate to 0.06 inside the for statement, then setting it to 0.00 on the next line :)

Remember to mark the thread as solved if this fixes your problem

I tried that and it doesn't work. I think I might know what is happening. The problem at the moment is that, even if the item name is Real Estate Forms 2D, after setting the TaxRate to 6% you're then immediately setting it back to 0%.
So I need to then do something with the tax rate before the foreach moves on to the next item and the tax rate is overwritten with the next value. I am just not sure what that is. So the code would look something like this:

foreach (ShoppingCartItem item in objCart.GetItem())
                            {
                                if (item.Name == "Real Estate Forms 2d")
                                {
                                    objCart.TaxRate = 0.06;
                                }
                                else
                                {
                                    objCart.TaxRate = 0.00;
                                }
                                // do something with objCart.TaxRate 
                            }

Just to clarify, if at least one item in the cart is Real Estate Forms 2d, the whole cart gets charged 0.06. If none of them are then it gets charged 0.00.

If thats the case then your best bet is a boolean to log if a taxable item is present:

bool isTaxable = false;
foreach (ShoppingCartItem item in objCart.GetItem())
{
   if (item.Name == "Real Estate Forms 2d")
   {
       isTaxable =true;
   }
} 
if(isTaxable)
{
     objCart.TaxRate = 0.06
}
else
{
     objCart.TaxRate = 0.00
}
}

I see what you are doing here but it still doesn't work for some reason. I don't know why because that code logic looks correct. It is still not giving a tax for any items I select and you are right it should tax the Real Estate Forms 2d ONLY and not the other items

Hmm...if that last code didnt work then something more fundamental is wrong. In order to tax only the taxable items then you'll need a different approach. The following will calculate a tax total for JUST the taxable items:

double tax = 0;
foreach (ShoppingCartItem item in objCart.GetItem())
{
   if (item.Name == "Real Estate Forms 2d")
   {
       tax += (0.06*item.Price);
   }
}

I've made a leap here and assumed you store the items price inside the item object. This will calculate the total tax for the shopping cart.

However, if the other code hasnt worked, this probably wont either. I would need to see the rest of your code to know for sure, but offhand i would suspect that a) your objCart.GetItem() isnt returning the item collection correctly or b) the item.Name comparison is failing. Are you sure item.name is stored as "Real Estate Forms 2d". If there is a typo or a case change in the names they wont match: "Real Estate Forms 2d" != "Real Estate Forms 2D".

Either attach your project here or put a breakpoint in and debug to check that all the items are being processed in the for each loop and that item.name is matching correctly.

Hmm...if that last code didnt work then something more fundamental is wrong. In order to tax only the taxable items then you'll need a different approach. The following will calculate a tax total for JUST the taxable items:

double tax = 0;
foreach (ShoppingCartItem item in objCart.GetItem())
{
   if (item.Name == "Real Estate Forms 2d")
   {
       tax += (0.06*item.Price);
   }
}

I've made a leap here and assumed you store the items price inside the item object. This will calculate the total tax for the shopping cart.

However, if the other code hasnt worked, this probably wont either. I would need to see the rest of your code to know for sure, but offhand i would suspect that a) your objCart.GetItem() isnt returning the item collection correctly or b) the item.Name comparison is failing. Are you sure item.name is stored as "Real Estate Forms 2d". If there is a typo or a case change in the names they wont match: "Real Estate Forms 2d" != "Real Estate Forms 2D".

Either attach your project here or put a breakpoint in and debug to check that all the items are being processed in the for each loop and that item.name is matching correctly.

Here is my entire code. This is the page load section:

Protected void Page_Load(object sender, System.EventArgs e)
		{
			try
			{
                //Require that this page be SSL secured
                this.SetSSL();
				
				if (!Page.IsPostBack)
				{
                    //Webexcellence.EComm.ShoppingCart.ToString() == Webexcellence.EComm.ShoppingCartItem.ToString();
					this.HeaderText = "Checkout";
					this.Title = "Indianapolis Bar Association";
					if ((Request.QueryString["print"] != null) && (Request.QueryString["print"] == "true"))
					{
						this.HeaderFile = "include/printheader.ascx";
						this.FooterFile = "include/printfooter.ascx";
					}

					bool blnNoCart = false;

					// get the user's cart
					if (Session["CartID"] != null)
					{
						ShoppingCart objCart = ShoppingCart.Resume(Convert.ToInt32(Session["CartID"]));
						if (objCart == null || objCart.Count == 0)
						{
							blnNoCart = true;
						}
						else
                        {

foreach (ShoppingCartItem item in objCart.GetItem())
{
   if (item.Name == "Real Estate Forms 2d")
   {
       tax += (0.06*item.Price);
   }
}
 rptCartItems.DataSource = objCart.GetItem();
                            rptCartItems.DataBind();

                            lblCartSubtotal.Text = String.Format("{0:c}", objCart.TotalValue);
                            lblCartTax.Text = String.Format("{0:c}", objCart.TaxRate * (dblShipping + objCart.TotalTaxableValue));
                            lblCartShipping.Text = String.Format("{0:c}", dblShipping);
                            lblCartTotal.Text = String.Format("{0:c}", objCart.TotalValue + (objCart.TaxRate * (dblShipping + objCart.TotalTaxableValue)) + dblShipping);

                            // set up the expiration years
                            if (ddlExpYears.Items.Count == 0)
                            {
                                ddlExpYears.Items.Add(new ListItem());
                                for (int i = 0; i < 10; i++)
                                {
                                    ddlExpYears.Items.Add((DateTime.Now.Year + i).ToString());
                                }
                            }

                            // fill in the user's data
                            if (User.Identity.IsAuthenticated)
                            {
                                PopulateMemberData();
                            }
                        }
					}
					else
					{
						blnNoCart = true;
					}

					// if the cart does not exist, show an appropriate message and do not show the checkout form
					if (blnNoCart)
					{
						pnlForm.Visible = false;
						Message = "Your cart is empty.  Please <a href='Resources-Publications.aspx'>continue shopping</a>.";
					}
				}
			}
			catch (Exception exc)
			{
				Message = "An error occurred: " + exc.Message;
			}
		}

Edited 7 Years Ago by mldardy: n/a

If you want us to debug your code for you, please attach the whole project. You can do so by clicking Go Advanced then Manage Attachments.

I would highly recommend debugging it for yourself though, as it is a fundamental skill that will help you with any coding you do.

Do you know how to insert breakpoints and debug line-by-line? Alternatively, include the System.Diagnostics namespace in your project and use the methods it exposes.

You need to check 2 things:
a) What is being returned by the .GetItem() method
b) Whether the Item.Name is stored exactly as "Real Estate Forms 2d"

If you want us to debug your code for you, please attach the whole project. You can do so by clicking Go Advanced then Manage Attachments.

I would highly recommend debugging it for yourself though, as it is a fundamental skill that will help you with any coding you do.

Do you know how to insert breakpoints and debug line-by-line? Alternatively, include the System.Diagnostics namespace in your project and use the methods it exposes.

You need to check 2 things:
a) What is being returned by the .GetItem() method
b) Whether the Item.Name is stored exactly as "Real Estate Forms 2d"

Debugging is going to be next to impossible with this project because there are so many errors within this project. I didn't create this code. This code was already in place I am just trying to fix/update things. in answer to your question:

a) I am not sure what exactly is being returned but I did a right click, Go to definition and got this: public ShoppingCartItem GetItem(int intItemID);

b) The Item.Name for "Real Estate Forms 2d" is stored in a sql table as Real Estate Forms 2d. I am not sure if that is what you mean.

Hmm, if its full of errors then theres no knowing where the issue is :p
Is it essential to use this code? If its full of bugs and not your own, if it was me i would start over.

One glaring issue straight away: public ShoppingCartItem GetItem(int intItemID) would suggest that the method returns a single Item based on an item ID.
This is definitely not going to work with your Foreach loop. You would need to implement a method which returned a collection of all the items.

I'm really not sure what help we can offer at this stage. All we have to work with is part of an error filled project.
The code i gave you will fix the foreach loop you originally posted about so this thread should be marked solved.

As for the rest of the problems, take it one error at a time or start fresh. If you build it from the ground up you can plan it properly and build a much cleaner solution than trying to kludge together someone elses bad start.

Hmm, if its full of errors then theres no knowing where the issue is :p
Is it essential to use this code? If its full of bugs and not your own, if it was me i would start over.

One glaring issue straight away: public ShoppingCartItem GetItem(int intItemID) would suggest that the method returns a single Item based on an item ID.
This is definitely not going to work with your Foreach loop. You would need to implement a method which returned a collection of all the items.

I'm really not sure what help we can offer at this stage. All we have to work with is part of an error filled project.
The code i gave you will fix the foreach loop you originally posted about so this thread should be marked solved.

As for the rest of the problems, take it one error at a time or start fresh. If you build it from the ground up you can plan it properly and build a much cleaner solution than trying to kludge together someone elses bad start.

I disagree with this. There is no error on this particular page and issue. I am unable to debug but that has nothing to do with what I am trying to do. I am trying to add on or updated this page by creating a condition where tax will show for a particular item. I don't think the problem is solved and the code you provided doesn't work. I believe the section of code posted in this thread is more than enough to solve the problem.

This question has already been answered. Start a new discussion instead.