WinForms textbox strange behaivor after 10 numbers - c#

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
}
}

Related

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;
}

C# Try Catch not working. Wanting an error message to display when characters appear

I am trying to get a try-catch to work. I have made a website and part of it is to withdraw cash. When I put characters in the withdraw text box the display text is: "Transaction Completed - take your money."
This is my code. I am a beginner programmer and I do not know what to do. Variables that have not been explicitly declared in this code have been declared globally.
protected void continue_btn_Click(object sender, EventArgs e)
{
// if the input of amount is not empty assign amount to a conversion integer of txtAmount.Text
if (txtAmount.Text != "")
{
try
{
amount = Convert.ToInt32(txtAmount.Text);
hBos.setWithdrawls(amount);
}
catch (Exception ex)
{
resultLbl.Text = ex.Message;
}
}
//if a radio button has been selected convert the selected amount and assign it to the amount variable
else
{
amount = Convert.ToInt32(amountRadioBtnList.SelectedValue);
}
//if amount is not a multiple of 10 display an error message
if (amount % 10 != 0)
{
resultLbl.Text = "Error- amount must be a multiple of 10";
return;
}
else
{
//if euro is selected convert to euro with exchange rate
if (currencyRadioBtnList.SelectedValue == "Euro")
{
decimalAmount = amount / hBos.getExchangeRate();
}
//decimal amount is equal to amount
else
{
decimalAmount = amount;
}
}
//if decimalAmount is greater than 250
//Displays error message
if (decimalAmount > 250)
{
resultLbl.Text = "Error - cannot withdraw more than £250";
return;
}
//invoke withdraw method using login. pin and decimal amount as parameters
success = hBos.withdraw(login, pin, decimalAmount);
//if the withdraw fails
//Displays error message
if (success == false)
{
resultLbl.Text ="Error - Insufficient funds";
}
//display message that transaction is sucessful
else
{
resultLbl.Text = "Transaction Completed - take your money";
}
//if the print receipt check box has been checked
// save withdrawl to decimal amount
//Then go to withdrawl reciept webpage
if(checkPrintedRecipt.Checked == true)
{
Session["withdrawl"] = decimalAmount;
Response.Redirect("WithdrawlReceipt");
}
}
If you want to see the exception message, add a return after you set it:
// if the input of amount is not empty assign amount to a conversion integer of txtAmount.Text
if (txtAmount.Text != "")
{
try
{
amount = Convert.ToInt32(txtAmount.Text);
hBos.setWithdrawls(amount);
}
catch (Exception ex)
{
resultLbl.Text = ex.Message;
return;
}
}
Much as you already have for some other failure conditions. At the moment, your catch sets a message but the method then continues. And then it attempts to withdraw 0 and succeeds.
There are a few other issues with this code - amount and decimalAmount are apparently fields rather than local variables. That fact is hiding the fact that there appear to be control flow paths in this logic that fail to set decimalAmount to anything sensible and so the code will use whatever value was left over from previous usage. Prefer to declare your variables as close as possible to where they're used (use locals rather than fields, declare them inside the smallest block where they're needed) to uncover those types of errors.
Also, rather than Convert.ToInt32 inside a try/catch block, you might want to consider int.TryParse instead. That's a method that expects parsing to possibly fail and allows you to cope with that gracefully rather than having to throw and catch an exception.
Regardless of what you are doing in the rest of your code, your first if statement is ignored so the try-catch block is never observed.
The reason is that you have put some characters in your text box although your if block checks empty input!
When I put characters in the withdraw textbox the diplay text is:
Transaction Completed - take your money.
I think you were trying to code something like this :
if (txtAmount != null)
{
// try-catch block
}
This statement can be reasonable because it shows that you want to prevent the possible nullreferenceexception. The structre tha you have used here is a kind of contradiction

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

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)

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