C# Calculation Program - Inputs Textboxes - c#

When I hit the 'calculate' button, the 'additional programs' and 'installations' textboxes revert back to 0 and the 'bill' comes out to the base price for the given customer type. My code is below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Bus432_Assignment2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
const double RES_HOME = 99;
const double RES_HOME_ADD = 49;
const double ENT_ADD_PRO = 10;
const double ENT_BASIC = 249;
const double ENT_PER_PRO = 99;
const double ENT_ADD_INSTALL_CHARGE = .10;
const double UNLIM_BASIC = 999;
char customerType;
double addpro = 0;
double install = 0;
double bill = 0;
// Check to make sure type has been entered.
if (txtCustomerType.Text == "")
{
MessageBox.Show("Customer type is required.",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
txtCustomerType.Focus();
return;
}
// Get customer type
customerType = char.Parse(txtCustomerType.Text);
customerType = char.ToUpper(customerType);
txtCustomerType.Text = customerType.ToString();
// Check customer type, programs, installations
txtInstall.Text = install.ToString();
txtAddPro.Text = addpro.ToString();
if (customerType == 'H' || customerType == 'E')
{
if (txtInstall.Text == "")
{
MessageBox.Show("For home use customer plan, enter installations",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
if (txtInstall.Text == "")
{
txtInstall.Focus();
}
return;
}
}
else if (customerType == 'E' || customerType == 'H')
{
if (txtAddPro.Text == "")
{
MessageBox.Show("For enterprise or home use customer, enter additional programs",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
if (txtAddPro.Text == "")
{
txtAddPro.Focus();
}
return;
}
else if (customerType != 'E' || customerType != 'H' || customerType != 'U')
{
MessageBox.Show("Customer type must be E, H, or U.",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
//txtInstall.Focus();
return;
}
// Get Additional Programs and installations
addpro = double.Parse(txtAddPro.Text);
install = double.Parse(txtInstall.Text);
if (addpro < 0)
{
MessageBox.Show("Number of additional programs must not be negative.",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
txtAddPro.Focus();
return;
}
else if (install < 0 )
{
MessageBox.Show("Number of installations must not be negative.",
Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
txtInstall.Focus();
return;
}
}
// Calculate Bill
switch(customerType)
{
case 'H':
bill = RES_HOME + addpro * RES_HOME_ADD;
break;
case 'E':
bill = ENT_BASIC + addpro * ENT_PER_PRO *(1+ENT_ADD_INSTALL_CHARGE*(install-ENT_ADD_PRO));
break;
case 'U':
bill = UNLIM_BASIC;
break;
}
// Display the result.
txtBill.Text = bill.ToString("C");
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
}
}

Within the code, you have declared these two variables
double addpro = 0;
double install = 0;
Then after you have declared these, you are setting the text of the boxes to equal them, without ever setting their values to anything but 0.
txtInstall.Text = install.ToString();
txtAddPro.Text = addpro.ToString();
I am not too sure on what you are trying to achieve, so I cannot suggest what you should have there instead, however that is the source of your problems regarding displaying 0 within the text fields.

Related

C# Simple Calculator Form not validating correct operators?

I am trying to make a form using C# that is similar to a calculator.
I have to code a method named IsOperator that checks that the text box that’s passed to it contains a value of +, -, *, or /.
For some reason it is not validating correctly.
I've tried changing the || to && and reversing the returns to false and true but nothing works.
When I try putting other things in the operator text box that are not + / - * the results turn into 0. Nothing ends up validating.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SimpleCalculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalc_Click(object sender, EventArgs e)
{
try
{
if (IsValidData())
{
MessageBox.Show("Error");
}
else
{
decimal operand1 = Convert.ToDecimal(txtOperand1.Text);
string operator1 = txtOperator.Text;
decimal operand2 = Convert.ToDecimal(txtOperand2.Text);
decimal result = 0;
if (operator1 == "+")
result = operand1 + operand2;
else if (operator1 == "-")
result = operand1 - operand2;
else if (operator1 == "*")
result = operand1 * operand2;
else if (operator1 == "/")
result = operand1 / operand2;
result = Math.Round(result, 4);
txtResult.Text = result.ToString();
txtOperand1.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n\n" +
ex.GetType().ToString() + "\n" +
ex.StackTrace, "Exception");
}
}
public bool IsValidData()
{
return
//validate the operand1 text box
IsPresent(txtOperand1, "Operand 1") &&
IsDecimal(txtOperand1, "Operand 1") &&
IsWithinRange(txtOperand1, "Operand 1", 0, 1000000) &&
//validates the operator text box
IsPresent(txtOperator, "Operator") &&
IsOperator(txtOperator, "Operator") &&
//validates the operand 2 text box
IsPresent(txtOperand2, "Operand 2") &&
IsDecimal(txtOperand2, "Operand 2") &&
IsWithinRange(txtOperand2, "Operand 2", 0, 1000000);
}
private void btnExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
//is present
public bool IsPresent(TextBox textBox, string name)
{
if (textBox.Text == "")
{
MessageBox.Show(name + " is a required field.", "Entry Error");
textBox.Focus();
}
return false;
}
//is decimal
public bool IsDecimal(TextBox textBox, string name)
{
decimal number = 0m;
if (Decimal.TryParse(textBox.Text, out number))
{
return true;
}
else
{
MessageBox.Show(name + " must be a decimal value.", "Entry Error");
textBox.Focus();
return false;
}
}
//is within range
public bool IsWithinRange(TextBox textBox, string name, decimal min, decimal max)
{
decimal number = Convert.ToDecimal(textBox.Text);
if (number < min || number > max)
{
MessageBox.Show(name + "must be between" + min.ToString()
+ "and" + max.ToString() + ".", "Entry Error");
textBox.Focus();
return false;
}
return true;
}
//is a valid operator
public bool IsOperator(TextBox textBox, string name)
{
string operator1 = "";
operator1 = Convert.ToString(textBox.Text);
if (operator1 == "+" && operator1 == "-" && operator1 == "/" && operator1 == "*")
{
MessageBox.Show("Please enter a valid operator in the operator text box.", "Entry Error");
return false;
}
return true;
}
private void txtOperand1_TextChanged(object sender, EventArgs e)
{
this.txtResult.Text = "";
}
private void txtOperator_TextChanged(object sender, EventArgs e)
{
this.txtResult.Text = "";
}
private void txtOperand2_TextChanged(object sender, EventArgs e)
{
this.txtResult.Text = "";
}
}
}
Fist of all you should not use someString == "" instead use string.IsNullOrEmpty(someString) or string.IsEmptyOrWhitespace(someString). 1
Then IsPresent always returns false. You may change that method to
public bool IsPresent(TextBox textBox, string name)
{
if (!string.IsNullOrEmpty(textBox.Text))
{
return true;
}
MessageBox.Show(name + " is a required field.", "Entry Error");
textBox.Focus();
return false;
}
In the EventHandler your forgot a ! before IsValidData(). You you're showing an Error, when the data is valid and try to perform the calculation, when your data is faulty.
Your IsOperator Method contains in fact a logical issue. You want to return true, if the operator is any of the following chars +, -, *, \. So its easier to flip the if logic to something like this using LINQ
//is a valid operator
public bool IsOperator(TextBox textBox, string name)
{
string operator = textBox.Text;
if (new[] {"+", "-", "*", "/"}.Contains(operator))
{
return true;
}
MessageBox.Show("Please enter a valid operator in the operator text box.", "Entry Error");
return false;
}
I think your code also could benefit from using Exceptions instead of showing MessageBoxes as soon an error occurs.

Converting Distance using C#

Program Problem: I am trying to convert from one type of distance to the next after the user inputs the data. The user must select from one list to convert to the other list in distance. For example, selecting inches in one list to convert to yards in another list.
My code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Distance_Converter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ConvertButton_click(object sender, EventArgs e)
{
//int Inches = 1;
//int Feet = 12;
//int Yards = 36;
int distance_to_convert;
string lengthOption1;
string lengthOption2;
int inches_feet;
int inches_yard;
lengthOption1 = FromListBox.SelectedItem.ToString();
lengthOption2 = ToListBox.SelectedItem.ToString();
distance_to_convert = int.Parse(distancetoconvertTextBox.Text);
if ((FromListBox.SelectedIndex) != -1 && (ToListBox.SelectedIndex) != -1)
{
switch (lengthOption1)
{
case "Inches":
if (lengthOption2 == "Inches")
{
//object distancetoconvert = null;
ConvertedDistanceTextBox = distance_to_convert.ToString();
}
else if (lengthOption2 == "Feet")
{
inches_feet = distance_to_convert / 12;
ConvertedDistanceTextBox = inches_feet.ToString();
}
else if (lengthOption2 == "Yards")
{
inches_yard = distance_to_convert / 36;
ConvertedDistanceTextBox = inches_yard.ToString();
}
break;
case "Feet":
if (lengthOption2 == "Inches")
{
int feet_inches = distance_to_convert * 12;
ConvertedDistanceTextBox = feet_inches.ToString();
}
else if (lengthOption2 == "Feet")
{
ConvertedDistanceTextBox = distance_to_convert.ToString(); ;
}
else if (lengthOption2 == "Yards")
{
int feet_yard = distance_to_convert / 3;
ConvertedDistanceTextBox = feet_yard.ToString();
}
break;
case "Yards":
if (lengthOption2 == "Inches")
{
int Yards_inches = distance_to_convert * 36;
ConvertedDistanceTextBox = Yards_inches.ToString();
}
else if (lengthOption2 == "Feet")
{
int Yards_feet = distance_to_convert * 3;
ConvertedDistanceTextBox = Yards_feet.ToString();
}
else if (lengthOption2 == "Yards")
{
ConvertedDistanceTextBox = distance_to_convert.ToString(); ;
}
break;
}
}
}
private void Exitbutton_click(object sender, EventArgs e)
{
this.Close();
}
}
}
My dilemma: The code looks correct in every sense. However, when I try to convert from int to string on multiple occasions the IDE gives me a red line. The code won't compile and creates build errors. I am thinking that I will have to create a separate class to convert from int to string.
The error states: "Error CS0029 Cannot implicitly convert type 'string' to 'System.Windows.Forms.TextBox' "
It appears on line - 42, 47, 52, or any line that begins with ConvertedDistanceTextBox = .
My apologies, I am new to coding and I am trying to learn. And I am relatively new to stackoverflow.
You should set your string values to the text property of your textbox
ConvertedDistanceTextBox.Text = inches_yard.ToString();

Application Crashes when the user enter's a Letter in the textbox [duplicate]

This question already has answers here:
How do I make a textbox that only accepts numbers?
(41 answers)
Closed 5 years ago.
I created a guessing game application. When the user enters a letter it crashes. I want the textbox to only have integers. I was trying to create a validation so when the user enters a letter it will display a message only integers only. How can I add a validation to the program so where the user can only enter an integer?
I tried using this code but it still crashes:
double input = Convert.ToInt32(txtInput.Text);
if (Double.TryParse(txtInput.Text, out input))
{
txtInput.Text = Convert.ToString(input);
}
else
{
MessageBox.Show("Please enter a valid number.");
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double guess;
private void Form1_Load(object sender, EventArgs e)
{
Random rand = new Random();
guess = rand.Next(1, 101);
}
private void Clickbutton_click(object sender, EventArgs e)
{
double input = Convert.ToInt32(txtInput.Text);
if (Double.TryParse(txtInput.Text, out input))
{
txtInput.Text = Convert.ToString(input);
}
else
{
MessageBox.Show("Please enter a valid number.");
}
if (input == guess)
{
lblMessage.Text = "You Are Corrrect, You Win" + " " +
" \r\n Random Number was = " + Convert.ToString(guess);
}
else if (input > guess)
{
lblMessage.Text = "Number is too High, Try Again";
txtInput.Clear();
}
else if (input < guess)
{
lblMessage.Text = "Number is too Low, Try Again";
txtInput.Clear();
}
}
}
}
You can use the NumericUpDown control.
The advantage of this control, is that it does not only has a text box, but also only numbers can be entered, and there are two small buttons on the right to increase with 1 or decrease with 1 (at least by default).
Also, more properties can be set.
The official documentation can be found here
And below is an example how it looks:
At codeproject an extended version can be found.
Besides the answer with the NumericUpDown.
Just something to add. With some little adjustments your code will work.
private void Clickbutton_click(object sender, EventArgs e)
{
//// Convert.ToInt32 throws an exception if it fails
//// to parse the string to an integer
//// So you don't want to parse the input directly
////double input = Convert.ToInt32(txtInput.Text);
// Your second attempt is the goal
double input;
if (!Double.TryParse(txtInput.Text, out input))
{
MessageBox.Show("Please enter a valid number.");
return; //// We are done. Nothing more to do here
}
txtInput.Text = input.ToString();
if ( input == guess)
{
lblMessage.Text = "You Are Corrrect, You Win" + " "+
" \r\n Random Number was = " + Convert.ToString(guess);
}
else if (input > guess)
{
lblMessage.Text = "Number is too High, Try Again";
txtInput.Clear();
}
else if (input < guess)
{
lblMessage.Text = "Number is too Low, Try Again";
txtInput.Clear();
}
}

Ensure first and last characters of text box are numbers c#

Im currently creating a windows form that must only allow a password through when it matches certain criteria. Im close to finishing however im a bit stuck with one element. "the first and last characters of the password HAVE to be numbers".
looking at my current code how would i go about this because i have ZERO idea. so baby steps and patience would be appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace password_test
{
public partial class Form1 : Form
{
bool Finished = false;
private bool TestPassword(string passwordText, int minimumLength = 5, int maximumLength = 12, int minimumNumbers = 1, int minimumLetters = 1)
{
int letters = 0;
int digits = 0;
int minLetters = 0;
if (passwordText.Length < minimumLength)
{
MessageBox.Show("You must have at least " + minimumLength + " characters in your password.");
return false;
}
if (passwordText.Length > maximumLength)
{
MessageBox.Show("You must have no more than " + maximumLength + " characters in your password.");
return false;
}
foreach (var ch in passwordText)
{
if (char.IsLetter(ch)) letters++;
if (char.IsDigit(ch)) digits++;
if (ch > 96 && ch < 123)
{
minLetters++;
}
}
if (digits < minimumNumbers)
{
MessageBox.Show("You must have at least " + minimumNumbers + " numbers in your password.");
return false;
}
if (minLetters < minimumLetters)
{
MessageBox.Show("You must have at least " + minimumLetters + " letter in your password");
return false;
}
Finished = true;
return true;
}
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void butConfirm_Click(object sender, EventArgs e)
{
if (txtPassword.Text == txtRetypePassword.Text)
{
bool temp = TestPassword(txtPassword.Text, 10, 100, 1, 1);
if (Finished == true)
{
MessageBox.Show("Password Accepted");
Application.Exit();
//this.Hide();
//Form2 f2 = new Form2();
//f2.ShowDialog();
}
}
else
{
MessageBox.Show("Please ensure the passwords you have typed match");
return;
}
}
private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsLetterOrDigit(e.KeyChar))
{
e.Handled = true;
}
else
{
return;
}
}
private void txtRetypePassword_TextChanged(object sender, EventArgs e)
{
}
}
}
Before Finished = true; you can simply do your check:
if (!char.IsDigit(passwordText[0]) || !char.IsDigit(passwordText[passwordText.Length - 1]))
{
MessageBox.Show("The first and last characters of the password have to be numbers");
return false;
}
Finished = true;
You should also enforce a minimum length in your method.
Or you can use Regex Test Pattern
// ^\d = start with digit
// \d$ end with digit
// .{3,10} including start and ending, min 5 max 12
if (!Regex.IsMatch(str, #"\d.{3,10}\d$")
{
// Invalid
}
Use \D to reverse.

How to call GetPrice method by passing converted value into txtQty?

I'm not sure if I'm writing the call correctly. 'intQty' says doesn't exist in current context. So how would I go about fixing that?
txtQty.Text = getPrice(intQty);
txtPrice.Text = decPrice.ToString("C2");
//Also to compute the order total it has to be written as
Order Total = (Order Qty * Price) * (1 + Tax Rate)
what I have: decTotal = (intQty * decPrice) * (1 + fltTaxRate);
so would I replace the that with values I've already declared?
EDIT: 'intQty' is declared right under the btnCalculate_Click as 'int intQty;'
there's data validation underneath and some methods as well.
FULL CODE:
string sCboStates;
int intQty;
string sWrapperSample;
// data validation
try
{
intQty = Convert.ToInt32(txtQty.Text);
}
catch
{
MessageBox.Show("Contents are not numeric.",
"Quantity",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtQty.Focus();
return;
}
try
{
sWrapperSample = Convert.ToString(txtWrapperSample.Text);
}
catch
{
MessageBox.Show("Content's empty.",
"Wrapper Sample",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtLine1.Focus();
return;
}
try
{
sCboStates = Convert.ToString(cboStates.Text);
}
catch
{
MessageBox.Show("Content's empty.",
"States",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
cboStates.Focus();
return;
}
}
// Method 1
private decimal getPrice(int intQty)
{
decimal decPrice;
if (intQty <= 500)
{
decPrice = 1.25m;
}
else if (intQty >= 501 && intQty <= 1000)
{
decPrice = 1.05m;
}
else if (intQty >= 1001 && intQty <= 5000)
{
decPrice = .90m;
}
else if (intQty > 5001)
{
decPrice = .75m;
}
decPrice = Convert.ToDecimal(txtPrice.Text);
txtQty.Text = intQty.ToString();
return intQty;
}
//Method 2
private float getTaxRate(string sCboStates)
{
string sStates = "";
float fltTaxRate=0;
if (sStates == "CT")
{
fltTaxRate = 0.06f;
}
else if (sStates == "MA")
{
fltTaxRate =.0625f;
}
else if (sStates == "ME")
{
fltTaxRate = .085f;
}
else if (sStates == "NH")
{
fltTaxRate = .0f;
}
else if (sStates == "RI")
{
fltTaxRate = .07f;
}
else if (sStates == "VT")
{
fltTaxRate = .06f;
}
return fltTaxRate;
}
//Method 3
private void formatWrapperSample()
{
txtWrapperSample.Text = txtLine1.Text + " " +
Environment.NewLine +
txtLine2.Text + " " +
Environment.NewLine +
txtLine3.Text;
}
// Method 4
private Color GetColor(string sColorIn)
{
return Color.FromName(sColorIn);
//CALCULATIONS
decimal decTotal = 0;
//Call the price method by passing the numeric value and the text qty
txtQty.Text = getPrice(intQty);
txtPrice.Text = decPrice.ToString("C2");
// Compute the total
decTotal = (intQty * decPrice) * (1 + fltTaxRate);
txtTotal.Text = decTotal.ToString("C2");
}
private void cboWrapperColor_SelectedIndexChanged(object sender, EventArgs e)
{
//Label Color 'cboWrapperColor_Selected' is a typo
txtWrapperSample.BackColor = GetColor(cboLabelColor.Text);
}
private void cboFontColor_SelectedIndexChanged(object sender, EventArgs e)
{
txtWrapperSample.ForeColor = GetColor(cboFontColor.Text);
}
private void cboStates_SelectedIndexChanged(object sender, EventArgs e)
{
getTaxRate("P2");
}
private void btnClear_Click(object sender, EventArgs e)
{
txtLine1.Clear();
txtLine2.Clear();
txtLine3.Clear();
txtQty.Clear();
txtWrapperSample.Clear();
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
It looks like there is some code missing, is everything starting with //CALCULATIONS to the end of the code part of the GetColor() method?
At any rate, you're declaring and initializing intQty in your btnCalculate_Click event handler. This means that the rest of your program does not know about intQty (with the exception of GetPrice() since you're passing it in).
Declare intQty as a global variable at the top of your class and then set the correct value in btnCalculate_Click
That way when you go to do the calculations it will know about intQty
Also...
You are using exceptions to control program flow, which is generally considered bad practice.
Exceptions are for exceptional cases, because they are computationally expensive.
You should use Int32.TryParse() instead
txtQty.Text = getPrice(intQty);
For one your method returns Decimal - you can't assign it to String property. C# is stringly typed.

Categories