C# Validating event: test for blank textbox and number validation? - c#

So I'm trying to create a validating event that makes sure a textbox isn't empty and that the number entered doesn't exceed 2000. I've posted what I have but every time I run it I get a message that the exception wasn't handled because the "kwh = decimal.Parse(khtextBox.Text)" input is not in the correct format. The way I have it, the validating works if the number exceeds 2000, but not if the textbox is blank. What am I doing wrong? Also new to programming so please explain like you're talking to a 3 year old! Thanks :)
private void khtextBox1_Validating(object sender, CancelEventArgs e)
{
decimal kwh;
kwh = decimal.Parse(khtextBox1.Text);
bool blank = false;
if (blank)
{
MessageBox.Show("Please enter a valid number.");
}
if (kwh > 2000)
{
MessageBox.Show("Kilowatt-Hours cannot exceed 2000.");
e.Cancel = true;
}
}

Try using the decimal.TryParse method, which try to convert the string to a decimal and returns a bool value if the conversion succeed, for sample:
decimal kwh;
if (!decimal.TryParse(khtextBox1.Text, out kwh)) // check if the conversion has failed
{
MessageBox.Show("Please enter a valid number.");
e.Cancel = true;
}
else // conversion ok, you can use the kwh value
{
if (kwh > 2000)
{
MessageBox.Show("Kilowatt-Hours cannot exceed 2000.");
e.Cancel = true;
}
}

You clearly mention yourself what the issue is. The input has to be something that could be converted to decimal some number.
It seems like an issue with incorrect input. Could you try using TryParse instead or you could simply change that second 'if' block to 'else if'.
decimal outputKWH;
kwh = decimal.TryParse(khtextBox.Text, out outputKWH)

Related

WinForms textbox strange behaivor after 10 numbers

I'm trying to put some controls on my TextBox using Visual Studio 2019 WinForms.
So this is my big control
int myNumber;
private void txtNumberControl_TextChanged(object sender, EventArgs e)
{
try
{
if (sender != null)
{
myNumber = Convert.ToInt32(txtNumberControl.Text);
}
}
catch (Exception)
{
MessageBox.Show("You can write only numbers!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
As you can see from the code above, I'm trying to make sure that the user inputs only numeric values. The strange behavior starts after 10 numbers writed. So if I write 12345678912 it goes in catch and shows me the MessageBox error message.
Here is a picture of it (it's in Italian but the error is the same I just translated it).
myErrorMessage
But the most strange part is that I can put down how many 00000000000000000000000000 I want and It just works as expected.
I'm seeking for help, can someone gently explain me why is this happening?
Your program goes into the catch because the number you wanted to enter is now to high to be converted into an integer.
Max Value for an integer is: 2147483647
You've gone over that limit with: 12345678912
Because of that your program fails to convert and prints the message even tough your input is a legit number.
To actually check if the whole inputed string is a number even if it is over the integer limit. You can use .IsDigit() combined with .All() to check if any of the letters is not a number.
Example:
public bool CheckForNumber(string yourString) {
// Check if all chars in this string are digits.
if (yourString.All(char.IsDigit)) {
return true;
}
return false;
}
We can now use that function in combination with the User input to check if it is a valid number.
private void txtNumberControl_TextChanged(object sender, EventArgs e) {
// Check the text of the object that triggered this Event.
if (!CheckForNumber((sender as Control).Text)) {
MessageBox.Show("You can write only numbers!", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Try to parse the text into a long (is 0 if the input is invalid).
if (!long.TryParse(txtNumberControl.Text, out long number)) {
// Not validated
}
}

C# Windows Form FormatException was unhandled

I am trying to put a check in textbox for value not greater then 100 but i am getting formatExeception can anybody help in this regard.. Thanks in Advance.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (Int32.Parse(textBox1.Text) > 100)
{
MessageBox.Show("No. Of Elements Must be Less Then 100");
}
}
You need to surround your statement with a try-catch in case the content of the textbox cannot be parsed into Int32. Assuming you run into the exception, you can then get a message describing the reason for the error.
Probably better to use a Numeric Updown if you only want the user to enter numbers but the error is happening because the text in the textbox cannot be parsed to a number. Use int.TryParse. It wont throw an exception if it cannot parse the string to a number
int numElements = 0;
int.TryParse(textBox1.Text, out numElements);
if(numElements >100){
MessageBox.Show("No. Of Elements Must be Less Then 100");
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
int parsed = 0;
if (!int.TryParse(textBox1.Text), out parsed)
{
MessageBox.Show("No. You must enter a number!");
return;
}
if (parsed > 100)
{
MessageBox.Show("No. Of Elements Must be Less Then 100");
}
}
That property of Parse to throw exceptions on parsing error is quite Vexing. It is so Vexing, the Framework Developers added TryParse with the 2.0 version. If you want to parse strings, you should always be using TryParse once you get past the initial development phase.
Or ideally a appraoch to validation/input that does not allow faulty inputs (like the Numerical Up/Down Ken Tucker noted.
If you somehow lack access to TryParse, I wrote a copy of it way back:
//Parse throws ArgumentNull, Format and Overflow Exceptions.
//And they only have Exception as base class in common, but identical handling code (output = 0 and return false).
bool TryParse(string input, out int output){
try{
output = int.Parse(input);
}
catch (Exception ex){
if(ex is ArgumentNullException ||
ex is FormatException ||
ex is OverflowException){
//these are the exceptions I am looking for. I will do my thing.
output = 0;
return false;
}
else{
//Not the exceptions I expect. Best to just let them go on their way.
throw;
}
}
//I am pretty sure the Exception replaces the return value in exception case.
//So this one will only be returned without any Exceptions, expected or unexpected
return true;
}

TextBox accepts only int

I have a problem with my textbox. I wanted that one can manually set the interval of the x- and y-axis for a chart in the GUI over two textboxes. That works but when I type a char in or when I typed an int in and delete it, the program crashes immediately and I get a System.FormatException (without clicking the button to accept the changes). How can I solve it that one can just type in different signs without immediately crashing the program? My code below:
public void textBox2_TextChanged(object sender, EventArgs e)
{
x_axis_num = Convert.ToInt32(xAxisBox.Text, usC);
}
private void yAxisBox_TextChanged(object sender, EventArgs e)
{
y_axis_num = Convert.ToInt32(yAxisBox.Text);
}
That gets passed to another event:
chart1.ChartAreas[0].AxisX.Interval = x_axis_num;
chart1.ChartAreas[0].AxisY.Interval = y_axis_num;
In the line x_axis_num = Convert.ToInt32(xAxisBox.Text, usC);, you are taking whatever is in the text box and try to convert it to an integer value.
What do you think the conversion of "Hey, I'm not a number!" will do? It will crash horribly, basically because that text is not, and never will be, a number.
Instead, you can use the Int.TryParse method which will take any text and TRY to convert it to a number.
If the conversion is successful, then no problem. If it was not successful, then you get a false value on a flag indicating the text could not be converted.
Example:
int number;
bool result = Int32.TryParse(YourTextBox.Text, out number);
If the conversion is successful, then number has the value, otherwise, result is false so do something like this then:
if(result)
{
xAxisBox.Text = number.ToString();
x_axis_num = number;
}
else
{
xAxisBox.Text = string.Empty;
// Be careful here with what you set.
// This is the value you will set when the Text box has a non numeric value!
x_axis_num = 0;
}

C# TextBox to int() not working when no value is entered

I have just started programming in C#. I am trying to convert a string to int. Like this:
int.Parse(textBox1.Text);
This is working fine when I enter a value but this is giving me exception when nothing is entered and I press the button. What should I do? Is there a function to solve this? Thanks
Use int.TryParse instead, it doesn't throw exception if the parsing fails.
Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.
int number;
bool isValid = int.TryParse(textBox1.Text, out number);
if(isValid)
{
// parsing was successful
}
One way to approach this is by using int.tryParse() instead of just int.Parse(). You can then check the result to see if the input was in the correct format.
Here is a sample:
int userInput;
if(!int.TryParse(textBox1.Text, out userInput))
{
//error in input here
}
After executing, if int.TryParse() returns true, then you will have a valid value in the userInput variable.
Alternatively you can wrap it in a try-catch, but it is better to attempt the parse and handle it without exceptions if possible.
Put this following code under your button event. It will make sure that the text/numbers entered into the textbox are able to be converted into an integer. Also, it will make sure that the textbox has numbers/text entered.
if (textBox1.Text != "")
{
try
{
Convert.ToInt32(textBox1.Text);
}
catch
{
/*
Characters were entered, thus the textbox's text cannon be converted into an integer.
Also, you can include this line of code to notify the user why the text is not being converted into a integer:
MessageBox.Show("Please enter only numbers in the textbox!", "PROGRAM NAME", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
*/
}
}
/*
else
{
MessageBox.Show("Please enter numbers in the textbox!", "PROGRAM NAME", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
*/
This is simple. You can do this on your button click event:
int number;
if (int.TryParse(textbox1.Text, out number))
{
// number is an int converted from string in textbox1.
// your code
}
else
{
//show error output to the user
}
Try below given solution
<script type="text/javascript">
function myFunction() {
alert('Please enter textbox value.');
}
</script>
And in the button click event use below given logic.
if (TextBox1.Text == "")
{
//Call javascript function using server side code.
ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "myFunction()", true);
}
else
{
int value;
value = int.Parse(TextBox1.Text);
}

textbox to accept integers

I've found different help through this website but still can't seem to convert a string to int. I've tried many different ways. Here are two of them. On button_click I need to read the textboxes and convert them to int so I can perform standard logic on them. (a > b functions). Below the first section is what I'm using to force the use of numbers during entry into the text boxes.
private void write_button_Click(object sender, EventArgs e)
{
int mat_od1 = int.Parse(matod_box.Text); //Input string in wrong format.
int mat_id1 = int.Parse(matid_box.Text);
int fod1 = int.Parse(fod_box.Text);
int fid1 = int.Parse(fid_box.Text);
int hp1 = int.Parse(hp_box.Text);
//This next section is just to show something else I've tried.
decimal mat_od = Convert.ToDecimal(matod_box.Text); //Same error.
decimal mat_id = Convert.ToDecimal(matid_box.Text);
decimal fod = Convert.ToDecimal(fod_box.Text);
decimal fid = Convert.ToDecimal(fid_box.Text);
decimal hp = Convert.ToDecimal(hp_box.Text);
decimal pass_od = mat_od;
}
private void fod_box_TextChanged(object sender, EventArgs e)
{
try
{
int numinput = int.Parse(fod_box.Text);
if (numinput < 1 || numinput > 500)
{
MessageBox.Show("You must enter a number between 0 and 500.");
}
}
catch (FormatException)
{
MessageBox.Show("You need to enter a number.");
fod_box.Clear();
}
Any help would be appreciated.
instead of int.Parse() you should use int.TryParse(string,out int)
this way you would be able to chek the output and decide wether the string was correctly parsed or not
int i;string s="";
if(int.TryParse(s,out i))
{
//use i
}
else
{
//show error
}
The int.parse conversion should work, as in this sample:
string s = "111";
int i;
if (int.TryParse(s, out i))
{
Console.Write(i);
}
else
{
Console.Write("conversion failed");
}
Are you sure you actually provide legal input for your ints? In any case, you should use TryParse like I did in my sample. Theres no need to use try..catch where you can use boolean methods provided by the framework, which will get you the same result..
All depends on what you are allowing to be put in the text box.
If it might not be a string that can be converted to an integer, including blank, then something like
int value;
if (int.TryParse(SomeString, out value)
{
// it is an int
}
else
{
// it's not an int, so do nothing raise a message or some such.
}
In addition to using Int32.TryParse in the button Click event handler as others have pointed out, you need to be careful what you're doing in the TextBox Changed event handler. You're code here is flawed:
private void fod_box_TextChanged(object sender, EventArgs e)
{
try
{
int numinput = int.Parse(fod_box.Text);
...
}
catch (FormatException)
{
MessageBox.Show("You need to enter a number.");
fod_box.Clear();
}
Calling foo_box.Clear() will clear any text from the textbox, calling the TextChanged handler to be executed again (unless the TextBox was already empty). So if you enter a non-numeric value, your message box will be displayed twice - the first time when it attempts to parse your non-numeric value, the second time when it attempts to parse an empty string as a result of the call to Clear().
In general, I'd avoid doing validation in the Changed event handler.

Categories