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

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;

Related

C# Program is Getting Stuck in a void Method

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);
}

How do i subtract discount text box from total text box more than one time?

I have the total textbox and discount textbox , I need to subtract the discount from total value , the issue how i will save the total value in variable and subtract the discount from the total if i entered the discount more than one time for example :
total value = 500 and discount = 100 then total = 500 - 100 = 400 .
The case i need to solve it suppose i need to add more discount or change the discount value from 100 to 200 how i will program it to subtract 500 - 200 = 300
and not 400 - 200 = 200 .
I tried the following code textbox key
private void txtdiscount_KeyPress(object sender, KeyPressEventArgs e)
{
decimal total = Convert.ToDecimal(textOrderTotal.Text);
decimal discount = Convert.ToDecimal(txtdiscount.Text);
if (e.KeyChar == Convert.ToChar(Keys.Return))
{
total = Convert.ToDecimal(textOrderTotal.Text) - Convert.ToDecimal(txtdiscount.Text);
textOrderTotal.Text = total.ToString();
}
}
How can i subtract discount from total more than one time subtract from grand total , also how to prevent discount value = or greater than total value ?
You need to capture the Original Total. If you have a button which calculates the Total, you could use
private decimal _originalTotal = 0;
private void btnCalculate_Click(object sender, EventArgs e)
{
_originalTotal = decimal.Parse(textOrderTotal.Text);
}
Or if the Total itself is being manually entered,
private decimal _originalTotal = 0;
private void textOrderTotal_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Return || e.KeyCode == Keys.Tab)
{
_originalTotal = decimal.Parse(textOrderTotal.Text);
}
}
The idea is to capture the original total, before the discount is being applied. Now, you could apply the discount as
private void txtdiscount_KeyPress(object sender, KeyPressEventArgs e)
{
decimal total = _originalTotal;
decimal discount = Convert.ToDecimal(txtdiscount.Text);
if (e.KeyChar == Convert.ToChar(Keys.Return))
{
total = _originalTotal - discount;
textOrderTotal.Text = total.ToString();
}
}
Please note you need to do the calculation based on previous captured Original Total. Also note following code in OP
total = Convert.ToDecimal(textOrderTotal.Text) - Convert.ToDecimal(txtdiscount.Text);
You had already converted the Text in the two text boxes to decimal in first two lines in the method. You could reuse them instead of converting again. In this particular, we would use the captured original total instead.
total = _originalTotal - discount;

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

Calculate percentage if percentage sign is in the text

My project has a Textbox field which is named as txtdisc. I need to minus the entered value from another Textbox called txttotal. The problem is I need to minus the percentage if I enter the percentage sign. For example, if my total value is 1000 and my discount value is 2 then I need the answer as 998 and if the entered value is 2% I need the value as 980. I used _textchanged event for the calculation.
My code is:
private void txtdiscount_TextChanged(object sender, EventArgs e)
{
if (txtdiscount.Text.Length > 0 && lbltotal.Text != "")
{
decimal net = 0, total = 0, discount = 0;
total = Convert.ToDecimal(lbltotal.Text);
discount = Convert.ToDecimal(txtdiscount.Text);
net =total- discount;
lblnetamount.Text = net.ToString();
}
}
You could look for the percent sign using Contains
If found, you can remove it using Trim('%');
Then modify your calculation to do the percentage
if (txtdiscount.Text.Length > 0 && lbltotal.Text != "")
{
decimal net = 0, total = 0, discount = 0;
total = Convert.ToDecimal(lbltotal.Text);
if (txtdiscount.Contains("%"))
{
discount = Convert.ToDecimal(txtdiscount.Text.Trim('%'));
net = total - (total * (discount / 100));
}
else
{
discount = Convert.ToDecimal(txtdiscount.Text);
net = total - discount;
}
lblnetamount.Text = net.ToString();
}
Resources
String.Trim Method (Char[])
String.Contains Method (String)
Try this:
private void txtdiscount_TextChanged(object sender, EventArgs e)
{
if (txtdiscount.Text.Length > 0 && lbltotal.Text != "")
{
decimal net = 0, total = 0, discount = 0;
total = Convert.ToDecimal(lbltotal.Text);
discount = Convert.ToDecimal(txtdiscount.Text.Replace("%",""));
if(txtdiscount.Text.EndsWith("%")
discount = total * (discount/100);
net = total- discount;
lblnetamount.Text = net.ToString();
}
}
Explanation:
discount = Convert.ToDecimal(txtdiscount.Text.Replace("%",""));
If you have % in your text just strip it off.
if(txtdiscount.Text.EndsWith("%")
discount = total * (discount/100);
If txtdiscount.Text endswith % then caculate percentage discount, otherwise leave discount as it it.
Important
I suggest you to use decimal.TryParse method instead or Convert.ToDecimal
This could be better one:
private void txtdiscount_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtdiscount.Text) && !string.IsNullOrEmpty(lbltotal.Text))
{
decimal net = 0, total = 0, discount = 0;
total = decimal.TryParse(lbltotal.Text, out total);
discount = decimal.TryParse(txtdiscount.Text.Replace("%",""), out discount);
discount = txtdiscount.Text.EndsWith("%")?total * (discount/100):discount;
net = total- discount;
lblnetamount.Text = net.ToString();
}
}
You can use this code,
private void txtdiscount_TextChanged(object sender, EventArgs e)
{
if (txtdiscount.Text.Length > 0 && lbltotal.Text != "")
{
decimal net = 0, total = 0, discount = 0;
total = Convert.ToDecimal(lbltotal.Text);
if (txtdiscount.Text.IndexOf('%') != -1)
{
discount = total * Convert.ToDecimal(txtdiscount.Text.Split('%')[0])/100;
}
else
{
discount = Convert.ToDecimal(txtdiscount.Text);
}
net =total- discount;
lblnetamount.Text = net.ToString();
}
}
int discount, total = 1000, net;
if(txtdiscount.EndsWith("%"))
discount = total*Convert.ToInt32(txtdiscount.Substring(0, st.Length-1))/100;
else
discount =Convert.ToInt32(txtdiscount.Substring(0, st.Length-1));
net = total -discount;
Here we are just checking whether the string ends with '%'. If yes, we are stripping it off and calculating the percentage of the total.
Try below code:
Use Contains() method to find if textbox contains % symbol and Use Split() method to remove % from value:
private void txtdiscount_TextChanged(object sender, EventArgs e)
{
if (txtdiscount.Text.Length > 0 && lbltotal.Text != "")
{
decimal net = 0, total = 0, discount = 0;
total = Convert.ToDecimal(lbltotal.Text);
if(txtdiscount.Text.Contains('%'))
{
discount = Convert.ToDecimal(txtdiscount.Text.split('%')[0]);
net = total - total*discount/100;
}
else
{
discount = Convert.ToDecimal(txtdiscount.Text);
net =total- discount;
}
lblnetamount.Text = net.ToString();
}
}
Hope it will help you

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?

Categories

Resources