Responding to Invalid TextBox Entries - c#

Users enter numbers into textboxes, and the values are displayed on a graph. I want to be sure users type numbers in the textboxes, so I tried:
double xValue;
double yValue;
Double.TryParse(xTextBox.Text, out xValue);
Double.TryParse(yTextBox.Text, out yValue);
chart1.Series["data1"].Points.AddXY(xValue, yValue);
Double.TryParse() validates whether users type numbers, but I'm not sure how to code for when users don't type numbers. Double.TryParse() will assign xValue or yValue a 0--but I also want users to be able to enter 0 values so I cannot just code something like
if (xValue!=0 && yValue!=0)...
Something like
if (xTextBox.Text!="0") {
Double.TryParse(xTextBox.Text, out xValue);
}
seems like awkward code that will just get more. What's the standard way to make sure users entered a double?

TryParse returns a boolean which is true if the conversion succeeded, and false if it failed.
if (!Double.TryParse(xTextBox.Text, out xValue)) {
// handle a failure to convert here
}

Double.TryParse returns a boolean if parsing was a success, and you should check the results of Double.TryParse not the xValue and yValue.

First of all you need to take into consideration the user locale settings. For example in USA the decimal separator is . and in my country it is ,. So you need to specify the format when user enters double values or replace , with . and then parse values with Invariant culture.
Second Double.TryParse method returns bool value which you can use to check whether the entered value is successfully parsed as double.

Related

displaying decimal values depending on decimal places in string.format

I'm using String.Format for displaying validation messages. I'm trying to achieve a scenario where, if decimal is there, show 12.34, else don't show any decimal points like, 12.
I tried to achieve it by using type as number. My string is,
Please enter value between {1:N} and {2:N}. // Displays 1.00 and 2.00
Please enter value between {1:N0} and {2:N0}. // Displays 1 and 2
What I should do to fix this? I need comma separation depending on culture. Using {1:G} will not provide that.
Try using :G . for isntance: Please enter value between {1:G} and {2:G}. Or {1:0.##}
The 0 means a digit will always be shown. Use a # to show optional digits.
{1:0.##}

How do I parse an integer, using the rule that +5 is not valid but 5 is?

My program asks the user to input a number from 1 - 10 in a text box in. When I the user inputs the number I have it converted into an int, by using this:
if (!int.TryParse(inputBox.Text, out input))
I used the ! because if the number cannot be TryParse'd into a int it throws an error to the user.
This works, until I enter a number that begins with a +, for example +5, or +1. It isn't catching the fact that there is a + in front of the int. If I enter more than one + it throws an error like it should.
How would someone make an error proofing line(s) of code that checks for this type of input?
I think you want to allow 1-10 without the positive sign (+).
int number;
var input = numberTextBox.Text;
if (!input.StartsWith("+") && int.TryParse(input, out number))
{
//valid input, check if it's between 1-10
}
But I think the requirement is really strange. "+10" is considered the same as "10", it is a valid input.
There is an overload of Int32.TryParse that accepts a NumberStyles value and an IFormatProvider. - https://msdn.microsoft.com/en-us/library/zf50za27(v=vs.110).aspx
The default used by Int32.TryParse is NumberStyles.Integer, which allows leading and trailing whitespace, and leading signs.
int.TryParse("+5", NumberStyles.None, NumberFormatInfo.InvariantInfo, out x), for example, returns false - however, it also returns false for -5, since the option to include a leading sign doesn't differentiate between a + and -. This is a hint that you probably shouldn't either, "+5" is every bit an integer as "5" and "-5".
You can remove + from textBox at runtime or check + character as shown in below code
if (inputBox.Text.Contains("+"))
{
// throw or show message
return;
}
if (!int.TryParse(inputBox.Text, out input))
{
}
If you want to show popup while press, you can check above condition in textbox TextChangeEvent,
Or use keypress event to restrict input.

validating decimal numbers in culture

can anyone please explain why, in 'en-GB' culture formatting, the decimal.Parse() function would return 15 for 1,5?
I see the same result for 'de' culture when inputting 1.5, the return is 15.
I know this is programmatically correct, I'm just trying to understand why this is correct. I've Googled this and come up with nothing :(
i'm trying to validate user inputs against culture, and populating the input field with a 0 when the parse fails, but populating the field with 15 when they've entered 1,5 doesn't feel right, i feel like it should be "failing" when a 1,5 is entered for english formating, instead of returning 15.
try {
validateSource.Text = decimal.Parse(validateThis, NumberStyles.Number, UserCulture).ToString();
} catch {
validateSource.Text = "0";
}
, is the NumberGroupSeparator in the UK culture. There's no validation in terms of how many digits are in each group. So "1,2,3" would be parsed as 123, even though that's not how we'd normally expect it to be written.
While it would make sense for parsing to check the NumberGroupSizes property, it simply doesn't.
You could emulate this check in a very primitive fashion by formatting the result of parsing, and see whether that's equal to the original input:
decimal value;
if (decimal.TryParse(text, NumberStyles.Number, culture, out value))
{
if (text != value.ToString("N", culture))
{
// Okay, looks like something's up... report an error
}
}
Of course, that would the stop someone from entering "1234.56" as it would expect "1,234.56"... you might want to check multiple pattern formats, e.g. "N" and "G", to see whether it matches any of them.

How to know the data type of value entered by user at runtime in textbox?

How to know the data type of value entered by user at runtime in textbox?
My simple example:
I've tried it by using GetType(), but it was useless, it always shows System.String, whether I enter int or String.
If the user has typed text into a textbox, that's always a string. It's never an int. You can parse the text as an integer, but the input itself is still text.
You could speculatively try to parse it in different ways:
int intValue;
if (int.TryParse(text, out intValue)
{
... use intValue, then return?
}
decimal decimalValue;
if (decimal.TryParse(text, out decimalValue)
{
... use decimalValue, then return?
}
But fundamentally you need to understand that the user input is always a string, and how you use that string is up to you.

Convert string value into decimal with proper decimal points

i have value stored in string format & i want to convert into decimal.
ex:
i have 11.10 stored in string format when i try to convert into decimal it give me 11.1 instead of 11.10 .
I tried it by following way
string getnumber="11.10";
decimal decinum=Convert.ToDecimal(getnumber);
i tried this also
decinum.ToString ("#.##");
but it returns string and i want this in decimal.
what could be the solution for this?
As already commented 11.1 is the same value as 11.10
decimal one=11.1;
decimal two=11.10;
Console.WriteLine(one == two);
Will output true
The # formatter in the to string method means an optional digit and will supress if it is zero (and it is valid to suppress - the 0 in 4.05 wouldn't be suppressed). Try
decinum.ToString("0.00");
And you will see the string value of 11.10
Ideally you actually want to use something like
string input="11.10";
decimal result;
if (decimal.TryParse(input,out result)) {
Console.WriteLine(result == 11.10);
} else {
// The string wasn't a decimal so do something like throw an error.
}
At the end of the above code, result will be the decimal you want and "true" will be output to the console.
this will work perfectly
string getnumber = "11.10";
decimal decinum = Math.Round(Convert.ToDecimal(getnumber), 2);
A decimal datatype stores a value. The value of 11.1 is identical to that of 11.10 - mathemtically, they're the exact same number, so it's behaving properly.
What you seem to want is to display the number as 11.10, but that's up to the code that displays it - I don't know if you're writing to log file, displaying on a web-page or any other format - but that is independent of the internal representation of the decimal datatype.
there is no solution, This is expected behaviour.
11.10 in string = 11.1 in number
you cant store zeros on the decimal part, otherwise 11.10 would be different than 11.100, which is true if you are talking about strings but not if you are talking about numbers.
I think your problem is on a presentation level only. Why dont you explain better what you want to do.
11.10 expressed as a decimal is 11.1, just like it is 11.100000000000000000000000000000000000.
For mathematical processes, don't worry about how it displays itself. If you are displaying the value then converting it into a string is no biggie either. Remember that
decinum.ToString ("#.##");
is returning a string (from the 'ToString' function) and not converting the 'decinum' to a string.
string getnumber = "11.10";
double decinum = double.Parse(getnumber);

Categories