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
Related
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;
I'm new to C# and I'm trying to do a simple task. I'm trying to make an if statement for my program where if the user enters a number less than 100, it multiplies by .1 and shows the answer in a message box. But everytime I run the program the message box gives me back 0 for an answer rather than 6.5 for 65 for example. I am probably just missing something easy in my code here, please take a look.
public partial class Form1 : Form
{
private double discountAmt;
public Form1()
{
InitializeComponent();
}
private void DiscountCalculation(object sender, EventArgs e)
{
double Price = 0;
double.Parse(PriceBox.Text);
if (Price < 100)
{
discountAmt = (Price * .1);
MessageBox.Show(" The discount is " + discountAmt.ToString());
}
}
}
}
Look at this line:
double.Parse(PriceBox.Text);
It parses the textbox, but doesn't do anything with the result. You want this:
double Price = double.Parse(PriceBox.Text);
Even better is to use double.TryParse(), and also when working with money use the decimal type rather than double.
private void DiscountCalculation(object sender, EventArgs e)
{
decimal Price = 0.0m;
if (decimal.TryParse(PriceBox.Text, out Price) && Price < 100)
{
discountAmt = (Price * .1);
MessageBox.Show($"The discount is {discountAmt}");
}
}
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;
I am in a basic C# programming class, and I have been understanding everything up until I had to do the following exercise. If someone could check my code and help me out, that would be fantastic. I'm getting three different errors (CS1620, CS0266, and CS1955) in this code. I had a classmate try to help me out, but that did not work out so well.
Here is the exercise prompt:
Piecework workers are paid by the piece. Workers who produce a greater quantity of output are often paid at a higher rate.
Form: Use text boxes to obtain the person’s name and the number of pieces completed. Include a Calculate command button to display the dollar amount earned. You will need a Summary button to display the total number of pieces, the total pay, and the average pay per person. A clear button should clear the name and the number of pieces for the current employee.
Include validation to check for missing data. If the user clicks on the Calculate button without first entering a name and number of pieces, display a message box. Also, you need to make sure to not display a summary before any data are entered; you cannot calculate an average when no items have been calculated. You can check the number of employees in the Summary event procedure or disable the Summary command button until the first order has been calculated.
Pieces completed Price paid per piece for all pieces
1-199 .50
200-399 .55
400-599 .60
600 or more .65
Code:
public partial class pieceworkForm : Form
{
//Declare variables.
int tpiece = 0;
int numemp = 0;
float tpay = 0;
public pieceworkForm()
{
InitializeComponent();
}
private void exitButton_Click(object sender, EventArgs e)
{
//Closes form.
this.Close();
}
private void printButton_Click(object sender, EventArgs e)
{
//Prints form.
printForm1.PrintAction = System.Drawing.Printing.PrintAction.PrintToPreview;
printForm1.Print();
}
private void calcButton_Click(object sender, EventArgs e)
{
//Converts pieces to integer.
int pieces = 0;
pieces = int.Parse(piecesTextBox.Text.Trim());
//Calculates pay based on number of pieces completed.
float pay = calcButton(pieces);
//Display the formatted text in the pay label
payMaskedTextBox.Text = string.Format("C", pay);
payMaskedTextBox.Visible = true;
//Counts employees on click.
numemp = numemp + 1;
//Total pieces made.
tpiece = tpiece + pieces;
//Total pay.
tpay += pay;
//Enable summary button.
sumButton.Enabled = true;
}
private void clearButton_Click(object sender, EventArgs e)
{
//Clears form.
empTextBox.Text = string.Empty;
piecesTextBox.Text = string.Empty;
payMaskedTextBox.Text = string.Empty;
}
private void callButton_Click(object sender, EventArgs e)
{
//Confirm clear.
if ((MessageBox.Show("Do you want to clear this form?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes))
{
// Call the regular "Clear" button handler, as if it had been clicked as well.
clearButton_Click(sender, e);
//Reset everything to zero.
tpiece = 0;
tpay = 0;
numemp = 0;
// Make summary groupbox invisible.
summaryGroupBox.Visible = false;
// And disable summary button until new pay is entered.
sumButton.Enabled = false;
}
}
private void empTextBox_TextChanged(object sender, EventArgs e)
{
//Show message if field is empty.
if (string.IsNullOrWhiteSpace(empTextBox.Text))
{
MessageBox.Show("Please enter an employee name.");
}
}
private void piecesTextBox_TextChanged(object sender, EventArgs e)
{
//Show messgae if field is empty.
if (string.IsNullOrWhiteSpace(piecesTextBox.Text))
{
MessageBox.Show("Please enter the number of pieces completed.");
}
}
private float calc(int pieces)
{
float pay = 0;
switch (pieces)
{
case 0:
pay = 0;
break;
case 1: // 1 to 199
pay = pieces * 0.5;
break;
case 2: // 200 to 399
pay = pieces * 0.55;
break;
case 3: // 400 to 599
pay = pieces * 0.6;
break;
default:
pay = pieces * 0.65;
break;
}
return pay;
}
private void SetcalcButtonState()
{
// Assume false
calcButton.Enabled = false;
// Check for non-empty text
if (((empTextBox.Text.Trim().Length > 0) & (piecesTextBox.Text.Trim().Length > 0)))
{
int pieces = 0;
// TryParse will return true if the text is good as a number
if ((int.TryParse(piecesTextBox.Text.Trim(), pieces)))
{
calcButton.Enabled = true;
}
}
}
private void sumButton_Click(System.Object sender, System.EventArgs e)
{
//Show total pieces nd pay.
tpieceMaskedTextBox.Text = string.Format("{0}", tpiece);
tpayMaskedTextBox.Text = string.Format("C", tpay);
//Calculate and show average pay per employee.
avgMaskedTextBox.Text = string.Format("C", tpiece / numemp);
// Make the whole summary box visible
summaryGroupBox.Visible = true;
}
}
The specific problem areas are as follows:
CS1955 Non-invocable member 'pieceworkForm.calcButton' cannot be used like a method.
float pay = calcButton(pieces);
CS0266 Cannot implicitly convert type 'double' to 'float'. An explicit conversion exists (are you missing a cast?)
private float calc(int pieces)
{
float pay = 0;
switch (pieces)
{
case 0:
pay = 0;
break;
case 1: // 1 to 199
pay = pieces * 0.5;
break;
case 2: // 200 to 399
pay = pieces * 0.55;
break;
case 3: // 400 to 599
pay = pieces * 0.6;
break;
default:
pay = pieces * 0.65;
break;
}
return pay;
}
CS1620 Argument 2 must be passed with the 'out' keyword.
if ((int.TryParse(piecesTextBox.Text.Trim(), pieces)))
{
calcButton.Enabled = true;
}
CS1955 Non-invocable member 'pieceworkForm.calcButton' cannot be used
like a method.
Instead of calling a method you are calling an event handler. What you want to do is the following:
float pay = calc(pieces);
CS0266 Cannot implicitly convert type 'double' to 'float'. An explicit
conversion exists (are you missing a cast?)
You need to specify your real numbers as a float in order to save them into a float variable, as they are a double by default.
private float calc(int pieces)
{
float pay = 0f;
switch (pieces)
{
case 0:
pay = 0f;
break;
case 1: // 1 to 199
pay = pieces * 0.5f;
break;
case 2: // 200 to 399
pay = pieces * 0.55f;
break;
case 3: // 400 to 599
pay = pieces * 0.6f;
break;
default:
pay = pieces * 0.65f;
break;
}
return pay;
}
CS1620 Argument 2 must be passed with the 'out' keyword.
Passing any values by reference must be explicitly defined using the out keyword. You can read about it on MSDN.
if ((int.TryParse(piecesTextBox.Text.Trim(), out pieces)))
{
calcButton.Enabled = true;
}
I wrote this program using Arrays in C#. It's homework. I pretty much have everything written in the program but I am stuck on clearing the array. I thought I had it but I don't understand where it's not working.
The program is pretty straightforward. The user enters a score and hits the "add" button. Then the user can enter more scores (anything 0 to 100). If the user chooses "Display" the program will sort the entered scores and display them in a messagebox (done)
if the user presses the "Clear Scores" button the program should clear out the scores. I have it written to clear the text boxes, and I also wrote in there "Scores.Clear();" (Scores being the name of my list array) and then I returned the focus back to my scores entry text box so the user can enter another score.
The book I am using simply says to clear type NameOfList.Clear(); so I'm stuck on why it's not clearing. I can tell it isn't because if I type more scores it will add the total instead of restarting.
Here is my full program code. My clear starts about halfway down.
Thank you in advance.
{
public partial class frmScoreCalculator : Form
{
//declare a list array for scores
List<int> Scores = new List<int>();
//set total and average to 0
int Total = 0;
decimal Average = 0;
public frmScoreCalculator()
{
InitializeComponent();
}
//calculate the average by dividing the sum by the number of entries
private decimal CalculateAverage(int sum, int n)
{
Average = sum / n;
return Average;
}
private void frmScoreCalculator_Load(object sender, EventArgs e)
{
}
//closes the program. Escape key will also close the program
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
//clears the text boxes, clears the array, returns focus back to the score text box like a boss.
private void btnClear_Click(object sender, EventArgs e)
{
txtScore.Text = "";
txtCount.Text = "";
txtTotal.Text = "";
txtAverage.Text = "";
Scores.Clear();
txtScore.Focus();
}
//makes sure the score is within the valid range, calculates the average, adds to the number of
//scores entered, and adds to the total
private void btnAdd_Click(object sender, EventArgs e)
{
if (txtScore.Text == string.Empty)
{
txtScore.Focus();
return;
}
int Score = int.Parse(txtScore.Text);
if (Score > 0 && Score < 100)
{
Scores.Add(Score);
Total += Score;
txtTotal.Text = Total.ToString();
txtCount.Text = Scores.Count.ToString();
Average = CalculateAverage(Total, Scores.Count);
txtAverage.Text = Average.ToString();
txtScore.Text = string.Empty;
txtScore.Focus();
}
// if number is not valid, ask user for valid number
else
{
MessageBox.Show("Please enter a number between 0 and 100.", "ENTRY ERROR, DO IT RIGHT!");
}
// returns focus to txtNumber
txtScore.Focus();
txtScore.Text = "";
}
//display button
private void btnDisplay_Click(object sender, EventArgs e)
{
//sorts the scores low to high
Scores.Sort();
//displays scores in message box
string DisplayString = "Sorted Scores :\n\n";
foreach (int i in Scores)
{
DisplayString += i.ToString() + "\n";
}
MessageBox.Show(DisplayString);
}
}
}
You need to zero the variable Total at the same time as clearing the array.