I am having trouble understanding how to reference an Array in this program. Every time I display the result, it will only show the last total entered. I believe this is because I am not referencing it properly? I am curious as to why, and how to avoid this in future. It seems like a simple solution, but I cannot figure it out.
public partial class frmInvoiceTotal : Form
{
public frmInvoiceTotal()
{
InitializeComponent();
total[0] = 0.0m;
total[1] = 0.0m;
total[2] = 0.0m;
total[3] = 0.0m;
total[4] = 0.0m;
}
decimal[] total = new decimal[5];
// TODO: declare class variables for array and list here
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
if (txtSubtotal.Text == "")
{
MessageBox.Show(
"Subtotal is a required field.", "Entry Error");
}
else
{
decimal subtotal = Decimal.Parse(txtSubtotal.Text);
if (subtotal > 0 && subtotal < 10000)
{
decimal discountPercent = 0m;
if (subtotal >= 500)
discountPercent = .2m;
else if (subtotal >= 250 & subtotal < 500)
discountPercent = .15m;
else if (subtotal >= 100 & subtotal < 250)
discountPercent = .1m;
decimal discountAmount = subtotal * discountPercent;
decimal invoiceTotal = subtotal - discountAmount;
discountAmount = Math.Round(discountAmount, 2);
invoiceTotal = Math.Round(invoiceTotal, 2);
txtDiscountPercent.Text = discountPercent.ToString("p1");
txtDiscountAmount.Text = discountAmount.ToString();
txtTotal.Text = invoiceTotal.ToString();
for (int i =0; i < total.Length; i++)
{
total[0] = invoiceTotal;
}
}
else
{
MessageBox.Show(
"Subtotal must be greater than 0 and less than 10,000.",
"Entry Error");
}
}
}
catch (FormatException)
{
MessageBox.Show(
"Please enter a valid number for the Subtotal field.",
"Entry Error");
}
txtSubtotal.Focus();
}
private void btnExit_Click(object sender, EventArgs e)
{
string totalsString = " ";
foreach (decimal totals in total)
totalsString += totals + "\n";
MessageBox.Show("The totals are:\n" + totalsString + "\n");
// TODO: add code that displays dialog boxes here
this.Close();
}
}
i, nott?