C# Program is Getting Stuck in a void Method - c#

I'm writing a C# program using windows forms that acts as a cash register where the user enters in the item, quantity, and cost. It then displays the entry in a listbox and display the subtotal, calculated tax, and calculated total in 3 other text boxes. It works fine on the first entry, even though I notice it goes through the method to calculate and display subtotal twice when I run in debug. When I go to enter a second item and recalculate the subtotal the program will crash, and when ran in debug will continually loop through the method to calculate and update the text box I'm using for subtotal. It does calculate the new subtotal in the variables as it loops through the method, it just doesn't leave the method. I call this method inside the method that handles the button click event to add items to the list. I've included the code, any suggestions would be greatly appreciated.
private void textBox4_TextChanged(object sender, EventArgs e)
{
itemTotal = Decimal.Multiply(quantityValue, costValue);
if (itemCount == 1)
{
subtotal = itemTotal;
}
if (itemCount > 1)
{
subtotal = Decimal.Add(itemTotal, subtotal);
}
textBox4.Text = subtotal.ToString();
}

double total =0;
double subtotal = 0;
double tax = 0;
double taxrate = 0.14;
private void button1_Click(object sender, EventArgs e)
{
int qnt = int.Parse(qnttextBox.Text);
double price = double.Parse(pricetextBox.Text);
subtotal = subtotal +(qnt * price);
subtextBox.Text = subtotal.ToString();
tax = subtotal * taxrate;
taxtextBox.Text = tax.ToString();
total = subtotal + tax;
totaltextBox.Text = total.ToString();
StringBuilder builder = new StringBuilder(nametextBox.Text + " " + qnttextBox.Text + " " + pricetextBox.Text);
listBox1.Items.Add(builder);
}

Related

Calculate subtotal, sales tax, and order total

Okay, so I'm sure this has been asked before but I can't seem to find anything in relation. I'm trying to create an assignment for school. It's a lunch order menu where you can place your order. We have to calculate the subtotal, the sales tax, and the order total. I can't seem to figure out the right code to use and I'm not 100% sure on what to try here.
public partial class Form1 : Form
{
decimal subtotal = 0m;
decimal salesTax = 0m;
decimal orderTotal = 0m;
public Form1()
{
InitializeComponent();
rdoBurger.Checked = true;
rdoPizza.Checked = true;
rdoSalad.Checked = true;
}
private void btnExit_Click(object sender, EventArgs e)
{
Close();
}
private void clearTotals()
{
}
private void btnPlaceOrder_Click(object sender, EventArgs e)
{
if (sender is RadioButton)
{
clearTotals();
}
if (rdoBurger.Checked)
{
decimal subtotal = 6.95m;
subtotal = Convert.ToDecimal(lblSubtotal.Text);
}
This is what I have but it's not showing the actual subtotal, it's still blank. What am I missing here?
It's not a bad start. This is more like what I'd expect to see:
private void btnPlaceOrder_Click(object sender, EventArgs e)
{
// only ONE of these can be checked, so "else if" is used
if (rdoBurger.Checked)
{
subtotal = 6.95m;
}
else if (rdoPizza.Checked)
{
subtotal = 5.95m;
}
else if (rdoSalad.Checked)
{
subtotal = 4.95m;
}
// multiple of these could be checked, so only "if" is used
if (checkBox1.Checked)
{
subtotal = subtotal + 100.00m; // whatever this item costs
}
if (checkBox2.Checked)
{
subtotal = subtotal + 4.99m; // whatever this item costs
}
if (checkBox3.Checked)
{
subtotal = subtotal + 10.99m; // whatever this item costs
}
// compute the tax and the total:
salesTax = subtotal * 0.0775m;
orderTotal = subtotal + salesTax;
// output it to your labels/textboxes?
lblSubtotal.Text = "$" + subtotal.ToString("F2");
lblSalesTax.Text = "$" + salesTax.ToString("F2");
lblOrderTotal.Text = "$" + orderTotal.ToString("F2");
}
Radio buttons can only have a single button selected at a time in a container. In this case it appears that the GroupBox is the container. If you had several groups of radio buttons you could use GroupBox as a container and have one radio button selected in each GroupBox. So, you cannot set all the radio buttons checked property to true.
In your btnPlaceOrder_Click the sender can not posibly be a radio button. The sender is the button that was clicked to run the event code.
private void button1_Click(object sender, EventArgs e)
{
//Find the radio button that is selected
RadioButton rButton = groupBox1.Controls.OfType<RadioButton>().FirstOrDefault(r => r.Checked == true);
switch (rButton.Text)
{
case "Hamburger - $6.95":
subTotal = 6.95m;
break;
case "Pizza - $5.95":
subTotal = 5.95m;
break;
case "Salad - $4.95":
subTotal = 4.95m;
break;
}
//Add code to handle Add-on items
//For example - The first check box is "Add Onions" - $0.50
if (checkBox1.Checked)
subTotal += .5m;
lblSubTotal.Text = subTotal.ToString();
decimal tax = subTotal * .0775m;
lblTax.Text = tax.ToString();
decimal total = subTotal + tax;
lblTotal.Text = total.ToString();
}

C#: Update values of readonly textboxes after each click

I'm trying to update values in read-only text boxes "Number of Months" and "Balance" after each click. In the given context both of these should have a starting value of 0 when the application begins. They should be updated after each click with the number of months simply adding up (1, 2, 3, etc.). The balance should show a specific value added up with each click.
The balance is equal to the monthly savings amount with the return of interest compounded monthly, so it would be dependent on the amount of months generated after each click.
I can make the month counter tick after each click as you'll see in the code, but I can't figure out how to update the balance and display it after each activation of the "Next Month" button.
public partial class frmSavingsCalculator : Form
{
public frmSavingsCalculator()
{
InitializeComponent();
}
int months = 0;
double balance = 0;
private void btnNext_Click(object sender, EventArgs e)
{
double monthlypmt;
int annualrate;
if (double.TryParse(txtMonthlySavings.Text, out monthlypmt))
{
if (int.TryParse(txtAnnualInt.Text, out annualrate))
{
annualrate = annualrate / 100;
double monthlyrate = annualrate / 12;
double changerate = (1 + monthlyrate);
txtMonths.Text = months.ToString();
months++;
balance = monthlypmt + Math.Pow(changerate, months);
txtBalance.Text = balance.ToString("c");
balance++;
}
else
{
MessageBox.Show("Please insert valid interest rate.");
}
}
else
{
MessageBox.Show("Please insert valid number.");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
My form:
P.S. Here is the updated code, and yes I have additional problems!
namespace Assignment1_BTM380
{
public partial class frmSavingsCalculator : Form
{
public frmSavingsCalculator()
{
InitializeComponent();
}
int months = 0;
double balance = 0;
private void btnNext_Click(object sender, EventArgs e)
{
double monthlypmt;
int annualrate;
if (double.TryParse(txtMonthlySavings.Text, out monthlypmt))
{
if (int.TryParse(txtAnnualInt.Text, out annualrate))
{
double realannualrate = (double) annualrate / 100;
double monthlyrate = realannualrate / 12;
double interest = (monthlypmt * monthlyrate);
txtMonths.Text = months.ToString();
months++;
balance = monthlypmt + balance * (Math.Pow(1+monthlyrate,months));
txtBalance.Text = balance.ToString("c");
}
else
{
MessageBox.Show("Please insert valid interest rate.");
}
}
else
{
MessageBox.Show("Please insert valid number.");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
SO, if you have the patience, bear with me. I managed to get the two text boxes to react each time I click the "Next Month" button, only I can't seem to get the appropriate values in the Balance. According to my professor's example, after 12 months, the Balance should display $619.86, only it shows $868.06 in my Form. I think the problem is with the Balance calculation, which I hope some of you can comment on.
Thanks to everyone who took the time to reply!
You're actually doing it right, the problem is that you're always getting the same result after the initial calculation due to a variable type problem.
The problem is the fact that the local variable "annualrate" is Integer.
Initially it makes sense since you are forcing them to write an integer number in the text box. Yet problem arises when you make it an actual rate by dividing it by 100.
annualrate = annualrate / 100;
Unless the rate in the text box is greater or equal to 100 you will always get a rate of zero because mathematically the result of any number between 0 and 100 (not including 100) divided by 100 is always between 0 and 1 (not including 1). For example, 50% rate should give you 0.5 but will result into just 0 because of the Integer division.
An easy fix will be:
...
double realannualrate = annualrate / 100;
double monthlyrate = realannualrate / 12;
...
You might also want to consider moving calculations and initialization to a separate functions

c# - How to read back textbox and add 1 each time

I'm trying to make a clothing sale GUI for my friends clothing shop. So when I type in a price and number of items, it'll display the total price, calculate the discount and calculate the amount due. And then when I enter a new price and # of items for the next customer, It repeats the process. My code doesn't update the number of transactions and total sales($) it just resets it. I want to return the previous number of transactions and total sales and add it to the next calculation. Please help guys!
private void btnCalculate_Click(object sender, EventArgs e)
{
double numberofitems;
double price;
double totalprice;
double discount;
double amountdue;
double totalsales;
double transactions = 0;
// Total Price
numberofitems = double.Parse(txtBoxNumberOfItems.Text);
price = double.Parse(txtBoxPrice.Text);
totalprice = numberofitems * price;
txtBoxTotalPrice.Text = totalprice.ToString();
// Discount
discount = totalprice * 30 / 100;
txtBoxDiscount.Text = discount.ToString();
// Amount Due
amountdue = totalprice - discount;
txtBoxAmountDue.Text = amountdue.ToString();
// Total Sales
totalsales = amountdue;
txtBoxTotalSales.Text = totalsales.ToString();
// Number of Transactions
transactions++;
txtBoxTransactions.Text = transactions.ToString();
}
// Clear button
private void btnClear_Click(object sender, EventArgs e)
{
txtBoxNumberOfItems.Text = "";
txtBoxPrice.Text = "";
txtBoxTotalPrice.Text = "";
txtBoxDiscount.Text = "";
txtBoxAmountDue.Text = "";
txtBoxTotalSales.Text = "";
txtBoxTransactions.Text = "";
}
// Exit Button
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
OK if I understand your issue correctly transactions and total sales are getting reset, and as I mentioned before, it's because you set those variables in the btnCalculate_Click() method. So by default, every time you click on the calculate button they get reset to 0. This is due to variable scope, google it. To fix the problem, all you will need to do is make transactions and totalsales as class variables instead of the local method variables you have now.
// now class variables and can be seen by the whole class
double transactions = 0;
double totalsales;
private void btnCalculate_Click(object sender, EventArgs e)
{
// method variables which can only be seen by this method
double numberofitems;
double price;
double totalprice;
double discount;
double amountdue;
// Total Price
numberofitems = double.Parse(txtBoxNumberOfItems.Text);
price = double.Parse(txtBoxPrice.Text);
totalprice = numberofitems * price;
txtBoxTotalPrice.Text = totalprice.ToString();
// Discount
discount = totalprice * 30 / 100;
txtBoxDiscount.Text = discount.ToString();
// Amount Due
amountdue = totalprice - discount;
txtBoxAmountDue.Text = amountdue.ToString();
// Total Sales
totalsales += amountdue;
txtBoxTotalSales.Text = totalsales.ToString();
// Number of Transactions
transactions++;
txtBoxTransactions.Text = transactions.ToString();
}
Try something like this:
string objTextBox = t.Text;

Why is my List total not computing correctly? C#

I am supposed to get values entered into a text box, then display the total of the entered values, the average of the values, and the count of how many values have been entered.
So far I have coded:
List<int> intScoreList = new List<int>(20);
decimal decScoreAverage = 0m;
decimal decScoreTotal = 0m;
private void btnAdd_Click(object sender, EventArgs e)
{
int intScore = Convert.ToInt32(txtScore.Text);
int intScoreCount = 0;
intScoreList.Add(intScore);
for (int i = 0; i < intScoreList.Count; i++)
{
intScoreList[0] = intScore;
decScoreTotal += intScoreList[i];
intScoreCount++; //correct
decScoreAverage = decScoreTotal / intScoreCount; //correct
}
When I enter test values of 30 then 40, the total gives me 110 (30 + 40 * 2) rather than 70 (30 + 40). Where am I going wrong?
Use Linq. On the add button click event simply add the parsed value. Then display the Avg, and Count.
List<decimal> scoreList = new List<decimal>();
private void btnAdd_Click(object sender, EventArgs e)
{
decimalnum;
if (decimal.TryParse(txtScore.Text, out num))
{
scoreList.Add(num);
}
// Assign to count label Text property = scoreList.Count;
// Assign to average label Text property = scoreList.Average();
}
Now imagine the ability to reset all the user's input:
private void btnReset_Click(object sender, EventArgs e)
{
scoreList.Clear();
}
Utilizing the list instance you can easily add number's as entered and correctly parsed from the user. The Average Linq extension method will do all the math for you, no need to do it yourself.
To the commenters' (justified) point below, here's some more explanation.
You're total isn't computing correctly mainly because you are changing the first item of your recorded values: intScoreList[0] = intScore;. By altering it, you are interfering with the sum.
A much clean operation consists of adding your new data to the array and recomputing the sum.
List<int> intScoreList = new List<int>(20);
decimal decScoreAverage = 0m;
decimal decScoreTotal = 0m;
private void btnAdd_Click(object sender, EventArgs e)
{
int intScore = Convert.ToInt32(txtScore.Text);
int intScoreCount = 0;
intScoreList.Add(intScore);
decScoreTotal = 0;
foreach(int i in intScoreList) {
decScoreTotal += i;
}
decScoreAverage = decScoreTotal / intScoreList.Count;
intScoreCount = inScoreList.Count;
}
Note that this isn't necessarily the most efficient implementation since as the number of values increase, the foreach loop will get more and more expensive. A better approach is to keep track of the current total and average and adjust them with the new value (which you can still add to the list for other purposes if you need).
The average is computed this way:
New_average = old_average * (count-1)/count + new_value /count
And here's the new code:
List<int> intScoreList = new List<int>(20);
decimal decScoreAverage = 0m;
decimal decScoreTotal = 0m;
private void btnAdd_Click(object sender, EventArgs e)
{
int intScore = Convert.ToInt32(txtScore.Text);
int intScoreCount = 0;
intScoreList.Add(intScore);
intScoreCount = inScoreList.Count;
decScoreTotal += intScore;
decScoreAverage = decScoreAverage * (intScoreCount- 1)/intScoreCount + intScore/intScoreCount;
}
Since the loop adds up all the items,
dont' you want
decScoreTotal = 0
before your for loop?

How to get the total values of each textboxes without pressing any buttons?

I am creating an expense tracking report using Visual Studio 2010 C# where the user can see the total of all the expenses while he/she is still typing the values for each expenses so that he/she could know if the total is equivalent or higher than her budget. My question is, how can I get the total of all the expenses the user is entering without having him/her press any button to calculate? Please help. Thanks
This is the screenshot of the form:
This is the code:
private void textBox3_TextChanged(object sender, EventArgs e)
{
tot = 0;
tot += int.Parse(textBox1.Text); // No error checking, just an example
tot += double.Parse(textBox2.Text);
textBox3.Text = tot.ToString();
}
You should catch TextChange event on every textbox (it could be one for all)
double tot = 0;
private void tb_TextChanged(object sender, EventArgs e)
{
// Update sum here
tot = 0;
tot += Int.Parse(Textbox1.Text); // No error checking, just an example
tot += Double.Parse(Textbox2.Text); // Be careful to decimal separator
TotalTextBox.Text = tot.ToString();
}

Categories

Resources