I have a form program that I need some help with. I need to calculate a total from a string. In this program I have a hardware store that lists items in a box. The user selects the item and then the quantity. The Receipt list box displays the items. I have this part just fine. However when I try to calculate what is in the box I am getting errors. Once calculated I need to enter in dollar amount to calculate change in a dialog box. Can anyone PLEASE help this newbie out???
namespace HardwareStore
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
ProductBox.Items.Add(new Hardware(){ItemNo = 1010, ProdName = "Hammer ", Price = (decimal)14.99d });
ProductBox.Items.Add(new Hardware(){ItemNo = 1056, ProdName = "Bag of Nails ", Price = (decimal)19.99d });
ProductBox.Items.Add(new Hardware(){ItemNo = 2001, ProdName = "Saw ", Price = (decimal)29.99d });
ProductBox.Items.Add(new Hardware(){ItemNo = 2005, ProdName = "Chainsaw ", Price = (decimal)69.99d });
ProductBox.Items.Add(new Hardware(){ItemNo = 3090, ProdName = "Ladder ", Price = (decimal)109.99d });
}
private void frmMain_Load(object sender, EventArgs e)
{
}
private void btnAddItem_Click(object sender, EventArgs e)
{
for (int i = 0; i < int.Parse(txtQuantity.Text); i++)
ReceiptBox.Items.Add(ProductBox.Items[ProductBox.SelectedIndex]);
}
private void ReceiptBox_SelectedIndexChanged(object sender, EventArgs e)
{
int total = 0;
//foreach (Hardware Current in ReceiptBox.Items) total += Current.
//double subtotal = Math.Round((ReceiptBox.Items), 2);
//double tax = Math.Round((subtotal * .075), 2);
//double total = subtotal + tax;
}
private void btnCalculate_Click(object sender, EventArgs e)
{
//lblSub.Text = "$" + subtotal.ToString();
//lblTax.Text = "$" + tax.ToString();
//lblTotal.Text = "$" + total.ToString();
lblSub.Visible = true;
lblTax.Visible = true;
lblTotal.Visible = true;
}
private void btnChange_Click(object sender, EventArgs e)
{
//MessageBox.Show("Change Due: $ ",);
}
}
}
ReceiptBox has no way of knowing what type of object is being stored in it. You will need to cast it as such
var subTotal = ReceiptBox.Items.Cast<Hardware>().Sum(item => item.Price);
Not too familiar with WinForms, but it looks like a better way of doing this would be utilizing ListBox.DataSource Property
Here is a stackoverflow thread on this matter