Check if TextBox input is a decimal number or not - C# - 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`
}

Related

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

C# if statement to test if value is not a number

I am trying to save the .text of a label to a database but sometimes that label is an infinity symbol. To catch for this I have created an if statement which checks if the label is a number or not and throws a message box up to tell the user. However more often than not the label will be a decimal number and the if statement throws up the message box. I was wondering if anyone could help me out please?
private void btnSaveResults_Click(object sender, EventArgs e)
{
btnClearData.Enabled = true;
if (System.Text.RegularExpressions.Regex.IsMatch(lblAerobicCap.Text, "[^0-9]"))
{
MessageBox.Show("Im sorry, there seems to have been an error in the inputting of the readings, please restart the test");
}
else
{
AthletesDetailsNew users = new AthletesDetailsNew();
DateTime dateTimeVariable = DateTime.Now;
users.Date_Of_Test = dateTimeVariable;
users.First_Name = comboBoxFirstName.Text;
users.Surname = comboBoxNewSurname.Text;
users.Age = int.Parse(comboBoxAge.Text);
users.Account_Number = int.Parse(comboBoxAccountNumber.Text);
users.Aerobic_Capacity = /*Math.Truncate*/(decimal.Parse(lblAerobicCap.Text));
DataClassDataContext dbCtx = new DataClassDataContext();
dbCtx.AthletesDetailsNews.InsertOnSubmit(users);
try
{
dbCtx.SubmitChanges();
MessageBox.Show("Data saved");
}
catch
{
MessageBox.Show("Data failed to save");
}
}
}
You should use the .TryParse() method for this.
for example:
decimal value;
bool isNumber = Decimal.TryParse(inputVariable, out value);
Use decimal.TryParse so in case of success you can reuse the result
decimal aerobicCap = -1;
if (!decimal.TryParse( lblAerobicCap.Text, out aerobicCap))
{
MessageBox.Show("Im sorry, there seems to have been an error in the inputting of the readings, please restart the test");
}
else
{
// code ...
users.Aerobic_Capacity = aerobicCap;
I think you need to trim the spaces from lblAerobicCap.Text prior to checking if the value is a number. Something like lblAerobicCap.Text = lblAerobicCap.Text.Trim().
lblAerobicCap.Text = lblAerobicCap.Text.Trim();
if (System.Text.RegularExpressions.Regex.IsMatch(lblAerobicCap.Text, "[^0-9]"))
{
MessageBox.Show("Im sorry, there seems to have been an error in the inputting of the readings, please restart the test");
}
[ ... ]
Better still avoid users entering anything but numbers. That way you do not have to validate the input.
For the digits use something like this:
void Control_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
Decimal:
void Control_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Decimal)
{
e.Handled = true;
}
}
I have used an extension method in the past which works nicely for me:
public static bool IsNumber(this object value)
{
return value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is int
|| value is uint
|| value is long
|| value is ulong
|| value is float
|| value is double
|| value is decimal;
}
object testObject = 0.1;
if (testObject.IsNumber()) { MessageBox.Show("Hooray!"); }

How Can You Calculate Multiple Textboxes?

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.

Textbox null value when parsing and messagebox notification

I have made a form which works perfectly fine when the fields are filled in. If you click the "convert" button with a blank textbox, it throws an error due to parsing a null value.
Obviously this means that I've declared my variable upon the button click.
I would also like a message box to pop up if the field is empty, to prompt the user to enter data.
Here is the code I have for the convert button:
private void exitButton_Click(object sender, EventArgs e)
{
//closes the form
this.Close();
}
private void convertButton_Click(object sender, EventArgs e)
{
decimal measurementDecimal = decimal.Parse(enterTextBox.Text);
//if else arguments for radio buttons
if (string.IsNullOrWhiteSpace(enterTextBox.Text))
{
MessageBox.Show("Please enter a value");
}
else if (inchesFromRadioButton.Checked && (inchesToRadioButton.Checked))
{
convertedTextBox.Text = measurementDecimal.ToString();
}
else if (inchesFromRadioButton.Checked && (feetToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal / 12).ToString();
}
else if (inchesFromRadioButton.Checked && (yardsToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal / 36).ToString();
}
else if (feetFromRadioButton.Checked && (inchesToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal * 12).ToString();
}
else if (feetFromRadioButton.Checked && (feetToRadioButton.Checked))
{
convertedTextBox.Text = measurementDecimal.ToString();
}
else if (feetFromRadioButton.Checked && (yardsToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal / 3).ToString();
}
else if (yardsFromRadioButton.Checked && (inchesToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal * 36).ToString();
}
else if (yardsFromRadioButton.Checked && (feetToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal * 3).ToString();
}
else if (yardsFromRadioButton.Checked && (yardsToRadioButton.Checked))
{
convertedTextBox.Text = measurementDecimal.ToString();
}
else
{
MessageBox.Show("Parameters not set. Please select a 'From' and 'To'");
}
Solution 1 : You can perform null or empty check before parsing the input value.and if it is invalid display warning and return from the method.
Try This:
private void convertButton_Click(object sender, EventArgs e)
{
//if else arguments for radio buttons
if (string.IsNullOrWhiteSpace(enterTextBox.Text))
{
MessageBox.Show("Please enter a value");
return;
}
/*Your remaining code here*/
decimal measurementDecimal = decimal.Parse(enterTextBox.Text);
Solution 2: You can use decimal.TryParse() method for checking the valid decimal value.
From MSDN:
Converts the string representation of a number to its Decimal
equivalent. A return value indicates whether the conversion succeeded
or failed.
private void convertButton_Click(object sender, EventArgs e)
{
decimal measurementDecimal ;
if (!decimal.TryParse(enterTextBox.Text,out measurementDecimal))
{
MessageBox.Show("Please enter a valid value");
return;
}
else
{
/*Your remaining code here*/
}

After "." the value entered must replace "00" with two digits only in the textbox

May be My Question is not seems like a good one but here is the Description:
I am creating an application in this in a form i have a textbox which is taking input from user here is my Code
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = string.Format("{0:0.##}", "0.00");
}
this will show value in textbox at pageload:0.00
Now after this if i click on backspace button of keyboard then
if (e.KeyChar.ToString() == ".")
{
e.Handled = true;
int b = textBox1.Text.LastIndexOf("00");
textBox1.SelectionStart = b;
}
else
{
string abc = "0";
string a = textBox1.Text.TrimStart(abc.ToCharArray());
textBox1.Text = a;
}
this code will lead me to here the textbox has now: .00 only
but after this when i enter some value then it will take values as;
2334.3423424
but i want to do like
2334.34
it means value should replace .00 only and user cant enter value after that.
This piece of code will restrict your user in entering only 2 digits after the decimal in your textbox.
//In key press event:
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (!char.IsControl(e.KeyChar))
{
TextBox tt = (TextBox)sender;
if (tt.Text.IndexOf('.') > -1 && tt.Text.Substring(tt.Text.IndexOf('.')).Length >= 3)
{
e.Handled = true;
}
}
If you mean to say you want to round up a number up to two decimal places use Math.Round(Double, Int32) function.
In your case you could call
double value = Convert.ToDouble(textBox1.Text);
double finalValue = Math.Round(value, 2);
textBox1.Text = finalValue.ToString();
Also make sure you validate the user input and make sure the user only enters numeric values.

Categories

Resources