How Can You Calculate Multiple Textboxes? - c#

I need help with my program in Visual Studio C#. The user must be able to enter a value into the four blank textboxes. The numbers in the textboxes should multiply with their set prices when the user clicks on Calculate. In other words, I want the four textboxes to multiply with their price.
The Form
Here's the calculation code. I managed to get the Children 5-12 textbox to calculate.
private void btnCalculate_Click (object sender, EventArgs e)
{
int FirstTextBoxNumber;
int SecondTextBoxNumber;
int answer;
try
{
Convert.ToInt32(tbSecondNumber.Text);
FirstTextBoxNumber = int.Parse("2");
SecondTextBoxNumber = int.Parse(tbSecondNumber.Text);
answer = FirstTextBoxNumber * SecondTextBoxNumber;
MessageBox.Show("Your total is £" + answer.ToString());
}
catch (FormatException)
{
MessageBox.Show("Please enter a decimal value");
}
}
How the form calculates

Try the following inside your btnCalculate_Click code:
bool isNumeric = true;
double answer = 0;
double firstTextBoxNumber = 0;
double thirdTextBoxNumber = 0;
double fifthTextBoxNumber = 0;
double seventhTextBoxNumber = 0;
int secondTextBoxNumber = 0;
int fourthTextBoxNumber = 0;
int sixTextBoxNumber = 0;
int eightTextBoxNumber = 0;
try
{
if (String.IsNullOrWhiteSpace(tbFirstNumber.Text) || String.IsNullOrWhiteSpace(tbSecondNumber.Text) || String.IsNullOrWhiteSpace(tbThirdNumber.Text) || String.IsNullOrWhiteSpace(tbFourthNumber.Text) || String.IsNullOrWhiteSpace(tbFifthNumber.Text) || String.IsNullOrWhiteSpace(tbSixNumber.Text) || String.IsNullOrWhiteSpace(tbSeventhNumber.Text) || String.IsNullOrWhiteSpace(tbEightNumber.Text))
{
isNumeric = false;
}
else
{
//Check if "Prices" are all Doubles
if (isNumeric)
{
isNumeric = double.TryParse(tbFirstNumber.Text.Replace("£", ""), out firstTextBoxNumber);
}
if (isNumeric)
{
isNumeric = double.TryParse(tbThirdNumber.Text.Replace("£", ""), out thirdTextBoxNumber);
}
if (isNumeric)
{
isNumeric = double.TryParse(tbFifthNumber.Text.Replace("£", ""), out fifthTextBoxNumber);
}
if (isNumeric)
{
isNumeric = double.TryParse(tbSeventhNumber.Text.Replace("£", ""), out seventhTextBoxNumber);
}
//Check if "Qty" are all Integers
if (isNumeric)
{
isNumeric = int.TryParse(tbSecondNumber.Text, out secondTextBoxNumber);
}
if (isNumeric)
{
isNumeric = int.TryParse(tbFourthNumber.Text, out fourthTextBoxNumber);
}
if (isNumeric)
{
isNumeric = int.TryParse(tbSixNumber.Text, out sixTextBoxNumber);
}
if (isNumeric)
{
isNumeric = int.TryParse(tbEightNumber.Text, out eightTextBoxNumber);
}
}
if (isNumeric)
{
answer = firstTextBoxNumber * secondTextBoxNumber;
answer += thirdTextBoxNumber * fourthTextBoxNumber;
answer += fifthTextBoxNumber * sixTextBoxNumber;
answer += seventhTextBoxNumber * eightTextBoxNumber;
MessageBox.Show("Your total is £" + answer.ToString());
}
else
{
MessageBox.Show("Please enter a decimal value");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The Try Catch block was changed because you should only handle system errors in Try blocks.
Please do note, I made the following assumptions:
The price can change, and can be changed to include cents and fractions of cents.
The price will only remove "£" and no other currency logos.
The Qty will always be an int since you can't have 1.5 children.
You are ok with the system error being shown in a message box to the
user instead of being logged somewhere.
Since this was quick, the code could be expanded on to remove some of the assumptions and to add rounding.

OK. I'm going to try to explain it to you:
You have 8 textboxes in your form.
They all have an identifier like textBox1, textBox2 etc..
What you want to take textBox1 and multiply it by textBox2. And this the same for the other 3 pairs. Then add up the total and display it in a messageBox.
I'll try to send you the right way:
private void btnCalculate_Click (object sender, EventArgs e)
{
int FirstPrice, SecondPrice, ThirdPrice, FourthPrice;
int FirstQnty, SecondQnty, ThirdQnty, FourthQnty;
int answer = 0;
try
{
FirstPrice = (int)TextBox1.Text.Replace("£", "");
SecondPrice = (int)TextBox2.Text;
ThirdPrice = (int)TextBox3.Text.Replace("£", "");
FourthPrice = (int)TextBox4.Text;
FirstQty = (int)TextBox5.Text.Replace("£", "");
SecondQty = (int)TextBox6.Text;
ThirdQty = (int)TextBox7.Text.Replace("£", "");
FourthQty = (int)TextBox8.Text;
answer = FirstPrice * FirstQty;
answer += SecondPrice * SecondQty;
answer += ThirdPrice * ThirdQty;
answer += FourthPrice * FourthQty;
MessageBox.Show("Your total is £" + answer.ToString());
}
catch (FormatException)
{
MessageBox.Show("Please enter a decimal value");
}
}
It might contain some spelling errors, but it should work.
Just replace the TextBox identifiers to the ones in your form.

Related

C# trouble in visual studio, can't get button click to execute lines properly

I am having some trouble with my code
The problem is every time I press the done button nothing calculates
I am using visual studio to code in C#
private void label1_Click(object sender, EventArgs e)
{
//Variable declaration
int Numtckets;
int NumberofULT = 35;
int NumberofSLT = 55;
int NumberofEZT = 42;
int Total = 0;
//Get input
Numtckets = int.Parse(Numberoftickesearned.Text);
//Processing
if (RADULT.Checked == true)
{
Total = NumberofULT * Numtckets;
TotalLbl.Text = "Your total is..." + Total;
}
else if (RADSLT.Checked == true)
{
Total = NumberofSLT * Numtckets;
TotalLbl.Text = "Your total is..." + Total;
}
else if (RADEZT.Checked == true)
{
Total = NumberofEZT * Numtckets;
TotalLbl.Text = "Your total is..." + Total;
}
else if (RADULT.Checked == false && RADSLT.Checked == false && RADEZT.Checked == false)
{
TotalLbl.Text = "Please enter the number of tickets" + Total;
}
}
}
}
I've tried editing the name properties and such with no luck. After I did that I still haven't gotten any results, any help would be appriecated.

How do I display the contents of an array without having the "0"'s in the display using a foreach loop?

public partial class frmEnhancedInvoiceTotal : Form
{
public frmEnhancedInvoiceTotal()
{
InitializeComponent();
}
private void BtnExit_Click(object sender, EventArgs e)
{
Close();
}
decimal[] decTotalofInvoicesArray = new decimal[5];
int intNumberOfInvoices = 0; //global variables
decimal decTotalOfInvoicesVariable = 0m;
decimal decAverageOfInvoices = 0m;
private void BtnCalculate_Click(object sender, EventArgs e)
{
//Convert = Class, .ToDecimal = method,
//when the user clicks the calulate button,
//we collect the subtotal, determine the appropriate discount,
//calculate the total and output the result to the screen.
//***EARN PARTIAL CREDIT PUT COMMENTS***
//Input
try
{
decimal decSubtotal = 0m; //initialize subtotal with a value of zero. We'll collect from the user later.
if (Decimal.TryParse(txtSubtotal.Text,
System.Globalization.NumberStyles.Currency, //now can type a $ sign and now break the code
System.Globalization.CultureInfo.CurrentCulture,
out decSubtotal)) //.tryparse attempts to convert but is a fail safe
//parse does 2 things - does something and tells you if works
decTotalofInvoicesArray[intNumberOfInvoices] = decSubtotal;
{
//Processing
decimal decDiscountPercent = 0m; //defining a new variable (discount percent) allow for real #, giving it a intial value of 0. Decimal variables you have to add m
if (decSubtotal >= 500m) //if my subtotal is 500 or more
{
decDiscountPercent = 0.2m; //inside braces is what will happen to the question above
//set discount rate to 20%
}
else if (decSubtotal < 500m && decSubtotal >= 250m) //if subtotal is between 250 & 500
//^^redundant because < 500 is already stated in the first if statement
//could just right else if(decSubtotal >=250m)
{
decDiscountPercent = 0.15m; //set discount rate to 15%
}
else if (decSubtotal < 250m && decSubtotal >= 100m) //if subtotal is between 100 and 250
{
decDiscountPercent = 0.1m; //set discount to 10%
}
//if subtotal is less than 100, dicounter percent is 0%
decimal decDiscountAmount = decDiscountPercent * decSubtotal;
decimal decTotal = decSubtotal - decDiscountAmount; //He is going so fast
//Aggregate Processing - across mutliple clicks of the calculate button
//old way of doing it = intNumberOfInvoices = intNumberOfInvoices + 1;
intNumberOfInvoices++; //value of variable plus one
//old way of doing it decTotalOfInvoices = decTotalOfInvoices + decTotal;
decimal decSum = 0m;
for (int intColIndex = 0; intColIndex < decTotalofInvoicesArray.Length; intColIndex++)
{
decSum += decTotalofInvoicesArray[intColIndex];
}
decTotalOfInvoicesVariable = decSum;
decAverageOfInvoices = decSum / decTotalofInvoicesArray.Length;
//Output
txtSubtotal.Text = decSubtotal.ToString("c");
txtDiscountPercent.Text = decDiscountPercent.ToString("p2"); //sending a numeric value and sending it to text = gives error
txtDiscountAmount.Text = decDiscountAmount.ToString("c"); //dot ToString makes value a text value and sends to textbox in form
//c=currency //"p2" - 2 = how many decimal places
//P = percentage
txtTotal.Text = decTotal.ToString("c");
//aggregate output
txtNumberOfInvoices.Text = intNumberOfInvoices.ToString();
txtTotalOfInvoices.Text = decTotalOfInvoicesVariable.ToString("c");
txtAverageOfInvoices.Text = decAverageOfInvoices.ToString("c");
//breakpoint analysis = click on the grey side bar and slowly work through the code to find the error. Essentially pause the code and run the code one point at a time
}
}
catch (FormatException) //you do not know what went wrong in the try part. It just errors anyways because SOMETHING went wrong
{
MessageBox.Show("Please enter valid numeric values.", "Entry Error");
}
catch (OverflowException) //something is to big
{
MessageBox.Show("Please try smaller numbers", "Entry Error");
}
catch //generic error code because why not
{
MessageBox.Show("An unexpected error has occured. Please try again.", "Entry Error");
}
}
private void BtnClearTotals_Click(object sender, EventArgs e)
{
//When resetting aggregate/global info - need to reset the variables AND the visual interface
intNumberOfInvoices = 0;
decTotalOfInvoicesVariable = 0m;
decAverageOfInvoices = 0m;
// txtNumberOfInvoices.Text = ""; //setting the variable to nothing. Erase the information in the text box
txtNumberOfInvoices.Clear();
txtTotalOfInvoices.Clear();
txtAverageOfInvoices.Clear();
}
private void TxtSubtotal_TextChanged(object sender, EventArgs e)
{
txtDiscountPercent.Clear();
txtDiscountAmount.Clear();
txtTotal.Clear();
}
private void BtnDisplayTotals_Click(object sender, EventArgs e)
{
String strOrderTotals = "";
//for (int intColIndex = 0; intColIndex < intNumberOfInvoices; intColIndex++)
//{
// strOrderTotals += decTotalofInvoicesArray[intColIndex] + "\n";
//}
foreach (decimal decTotalInvoices in decTotalofInvoicesArray)
{
if (strOrderTotals == "0")
{
strOrderTotals += decTotalInvoices + "\n";
}
}
MessageBox.Show(strOrderTotals.ToString());
}
private bool IsValidData()
{
return
IsPresent(txtSubtotal) && //did you type anyting
IsDecimal(txtSubtotal) && //make sure you types a real number
IsWithinRange(txtSubtotal, 0m, 1000m); //is the number in the range
}
private bool IsPresent(TextBox textBox) //send an entire textbox into method
{
if (textBox.Text == "")
{
MessageBox.Show(textBox.Tag.ToString() + " is a required field.", "Missing Entry"); //textbox is whatever is in the (TextBox textBox)
textBox.Focus();
return false;
}
return true;
}
private bool IsDecimal(TextBox textBox)
{
decimal decTestValue = 0m;
if (!Decimal.TryParse(textBox.Text, out decTestValue)) //! - dont succusfully tryparse
{
MessageBox.Show(textBox.Tag.ToString() + " must be a numeric value", "Entry Error"); //textbox is whatever is in the (TextBox textBox)
textBox.Focus();
return false;
}
return true;
}
private bool IsInteger(TextBox textBox)
{
int intTestValue = 0;
if (!Int32.TryParse(textBox.Text, out intTestValue)) //! - dont succusfully tryparse
{
MessageBox.Show(textBox.Tag.ToString() + " must be a whole number.", "Missing Entry"); //textbox is whatever is in the (TextBox textBox)
textBox.Focus();
return false;
}
return true;
}
private bool IsWithinRange(TextBox textBox, decimal decMin, decimal decMax)
{
decimal decTestValue = Convert.ToDecimal(textBox.Text);
if (decTestValue < decMin || decTestValue > decMax) //to small or to big
{
MessageBox.Show(textBox.Tag.ToString() + " must be between " + decMin.ToString() + " and " + decMax.ToString() + "." + "Out of Range"); //textbox is whatever is in the (TextBox textBox)
textBox.Focus();
return false;
}
return true;
}
}
}
Basically I have a invoice total windows form were the user inputs a subtotal value and total value is calculated based on the discount percent. In the assignment is says to create an array that hold up to five invoice totals. My problem is when I type lets say 2 subtotal values and click display totals the 2 number I typed in are displayed along with 3 zeros. I am wanting to know how to only display the number I inputted and not the zeros using a foreach loop.
It does not look like you are adding anything in your foreach.
foreach (decimal decTotalInvoices in decTotalofInvoicesArray)
{
if (strOrderTotals == "0")
{
strOrderTotals += decTotalInvoices + "\n";
}
}
MessageBox.Show(strOrderTotals.ToString());
Am I reading this right that you want to have each invoice shown, and do you want the total too? This code with a for loop should work. I
strOrderTotals = "My Invoices\n";
decimal decOrderTotals = 0;
for (int i = 0; i < decTotalofInvoicesArray.Length; i++)
{
if (decTotalofInvoicesArray[i] != 0)
{
strOrderTotals += "Invoice : " + decTotalofInvoicesArray[i] + "\n";
decOrderTotals += decTotalofInvoicesArray[i];
}
}
strOrderTotals += "Total of invoices: " + decOrderTotals;
MessageBox.Show(strOrderTotals.ToString());

Check if TextBox input is a decimal number or not - C#

My Goal: I want textbox to accept the decimal numbers like 123.45 or 0.45 or 1004.72. If the user types in letters like a or b or c, the program should display a message alerting the user to input only numbers.
My Problem: My code only checks for numbers like 1003 or 567 or 1. It does not check for decimal numbers like 123.45 or 0.45. How do I make my text box check for decimal numbers? Following is my code:
namespace Error_Testing
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string tString = textBox1.Text;
if (tString.Trim() == "") return;
for (int i = 0; i < tString.Length; i++)
{
if (!char.IsNumber(tString[i]))
{
MessageBox.Show("Please enter a valid number");
return;
}
}
//If it get's here it's a valid number
}
}
}
I am a newbie and Thanks for your help in advance. :)
use Decimal.TryParse to check if the string entered is decimal or not.
decimal d;
if(decimal.TryParse(textBox1.Text, out d))
{
//valid
}
else
{
//invalid
MessageBox.Show("Please enter a valid number");
return;
}
decimal.Tryparse returns true for string containing "," character and for example string like "0,12" returns true.
private void txtrate_TextChanged_1(object sender, EventArgs e)
{
double parsedValue;
decimal d;
// That Check the Value Double or Not
if (!double.TryParse(txtrate.Text, out parsedValue))
{
//Then Check The Value Decimal or double Becouse The Retailler Software Tack A decimal or double value
if (decimal.TryParse(txtrate.Text, out d) || double.TryParse(txtrate.Text, out parsedValue))
{
purchase();
}
else
{
//otherwise focus on agin TextBox With Value 0
txtrate.Focus();
txtrate.Text = "0";
}
}
else
{
// that function will be used for calculation Like
purchase();
/* if (txtqty.Text != "" && txtrate.Text != "")
{
double rate = Convert.ToDouble(txtrate.Text);
double Qty = Convert.ToDouble(txtqty.Text);
amt = rate * Qty;
}*/
}`enter code here`
}

How to display array elements, if the number of elements is a variable

I'm making a calculator in GUI, and I need some help.
When I enter some data in a text box, I need to store it in an array. This is how I thought of it.
int numOfPackages;//used to get user input
private void button3_Click(object sender, EventArgs e)
{
int[] weight = new int[numOfPackages];
for(int i = 0; i < numOfPackages; i++)
{
weight[i] = Convert.ToInt32(weightBox.Text);
}
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
}
And when I try to display the elements, it gives me the indexOutOfRange exception.
So, how do I display the elements of that array?
Thanks in advance.
This line
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
should be
foreach (int w in weight)
totalCostLabel.Text = "" + w;
Your current code iterates the array of weights, and tries to use the weight as an index into the array of weights, causing an index out of range exception.
Another problem is with the first loop: you are setting all values of weight to the same number:
weight[i] = Convert.ToInt32(weightBox.Text); // That's the same for all i-s
If weights are to be different, they should come from different weight boxes, or the string from a single weightBox should be processed in such a way as to produce multiple numbers (for example, by using string.Split).
You have multiple problems here. First is this:
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
This is iterating the weight array and using each value in that array. You then use that value as an index. Take the following example:
weight[0] = 0
weight[1] = 1
weight[2] = 15
In your code, the first two entries will work because there is an index of 0 and an index of 1. But when it gets to the last entry, it looks for an index of 15. You can fix this two ways, the first is to use a regular for loop:
for(int i=0; i < weight.Length; i++)
{
totalCostLabel.Text += weight[i];
}
This brings the second mistake. You aren't appending anything to your totalCostLabel in your code, you are just replacing the value. This will append all the values of weight together as one.
Another way to do this is to use the foreach loop:
foreach(int i in weight)
{
totalCostLabel.Text += i;
}
This is the same as above but you don't have to worry about indexing.
Bottom line, even after you fix your loop, you will probably need to fix the way that the label takes the text otherwise you won't get your desired result.
Maybe you wanted something more like?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
btnAdd.Enabled = false;
}
int[] weight;
int entriesMade;
int numOfPackages;
private void btnReset_Click(object sender, EventArgs e)
{
if (int.TryParse(numEntriesBox.Text, out numOfPackages))
{
weight = new int[numOfPackages];
entriesMade = 0;
btnReset.Enabled = false;
btnAdd.Enabled = true;
totalCostLabel.Text = "";
}
else
{
MessageBox.Show("Invalid Number of Entries");
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
int value;
if (int.TryParse(weightBox.Text, out value))
{
weight[entriesMade] = value;
weightBox.Clear();
totalCostLabel.Text = "";
int total = 0;
for (int i = 0; i <= entriesMade; i++)
{
total = total + weight[i];
if (i == 0)
{
totalCostLabel.Text = weight[i].ToString();
}
else
{
totalCostLabel.Text += " + " + weight[i].ToString();
}
}
totalCostLabel.Text += " = " + total.ToString();
entriesMade++;
if (entriesMade == numOfPackages)
{
btnAdd.Enabled = false;
btnReset.Enabled = true;
MessageBox.Show("Done!");
}
}
else
{
MessageBox.Show("Invalid Weight");
}
}
}

c# error: Input string not in correct format

I have a datagrid view which is editable. I'm getting the value of a cell and then calculate the value of another cell. To do this I have handled CellEndEdit and CellBeginEdit events.
quantity = 0, quantity1 = 0, quantity_wt1 = 0, quantity_wt = 0, ekundag = 0;
private void grdCaret_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
if (e.ColumnIndex == 1)
{
int val = int.Parse(value);
quantity = val;
ekundag = ekundag + quantity;
tbTotDag_cr.Text = ekundag.ToString();
}
if (e.ColumnIndex == 2)
{
float val = float.Parse(value);
total = val;
ekunrakam = ekunrakam + total;
tbTotPrice_cr.Text = ekunrakam.ToString();
}
grdCaret.Columns[3].ReadOnly = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void grdCaret_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
rate = 0;
quantity1 = quantity;
total1 = total;
rate = (total1 / quantity1);
if (e.ColumnIndex == 3)
{
grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = rate.ToString();
grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].ReadOnly = true;
// quantity = 0;
// total = 0;
}
}
In the grid I have columns as quantity, total and rate. I get the above error here:
if (e.ColumnIndex == 1)
{
int val = int.Parse(value);
quantity = val;
ekundag = ekundag + quantity;
tbTotDag_cr.Text = ekundag.ToString();
}
When I enter quantity and click on the total column in gridview. Please help me fix this
AFAIK the int.Parse() function can possibly cause this kind of exceptions.
Have you tried to check the value in the cell? Isn't it possible, that some other characters are in the cell, not only the numbers? White spaces for example.
The value you have entered into your Cell can't be parsed as Integer, so it will fail #
int val = int.Parse(value);
Your input string 'value' is not in a valid format to be parsed to an integer. Take a look at this: http://www.codeproject.com/Articles/32885/Difference-Between-Int32-Parse-Convert-ToInt32-and
try using Text instead of ToString()
string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.Text;
in place of
string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();

Categories

Resources