1

So, I'm working in C# and for some reason my conversion is throwing exceptions, the code is meant to execute when user presses a button, here is the code.

private void tbVerk6Breidd_KeyDown(object sender, KeyEventArgs e)
{
    int width = Convert.ToInt32(tbTextBox.Text); //Crashes here
}

Any help appreciated :)

Edit

Heki mentioned that KeyUp would be a better idea, that worked. Thanks :)

private void tbVerk6Breidd_KeyUp(object sender, KeyEventArgs e)
{
    int width = Convert.ToInt32(tbTextBox.Text);
}
Alexander Freyr
  • 569
  • 1
  • 6
  • 19
  • 7
    And what is in the textbox `tbTextBox.Text`? If it is anything that is NOT number, then it is supposed to throw an exception. – Paweł Mach Aug 31 '15 at 11:32
  • Can you write the exception message? – miguelbgouveia Aug 31 '15 at 11:32
  • Have you used the debugger to find out what `tbTextBox.Text` contains? Which exception is being thrown? – Micke Aug 31 '15 at 11:33
  • It will throw exception if there is value other than a number in `tbTextBox.Text` – Harshit Aug 31 '15 at 11:33
  • 8
    Let me guess: user entered `"one hundred two"` – Tim Schmelter Aug 31 '15 at 11:33
  • The program is throwing Input string was not in a correct format. – Alexander Freyr Aug 31 '15 at 11:39
  • As a side note, using the `Changed` event instead could be a better idea. I don't think you can be sure that the input have changed when you handle the `KeyDown` event. It should definitely have in `Changed` or `KeyUp`. If the user holds down `1` you won't catch the `11111111` input with `KeyDown`. – Heki Aug 31 '15 at 11:40
  • what you really need is input validation. you could also add an event which allows only integer values to be entered into the textbox. – user1666620 Aug 31 '15 at 11:40
  • Edit your own question (if you can) and put what the input string actually is. Blank textbox? Or what? Or please post this below what the string was in a comment like you just did. – Kevin Anderson Aug 31 '15 at 11:41
  • Take a look here : http://stackoverflow.com/questions/894263/how-to-identify-if-a-string-is-a-number – Emmanouil Chountasis Aug 31 '15 at 11:42
  • @Heki Changing KeyDown to KeyUp worked, thanks :) – Alexander Freyr Aug 31 '15 at 11:44
  • @AlexanderFreyr You're welcome. You should however, always think bad about your users. The input TimSchmelter and others have suggested may be quite likely. That or the user inputs space in front or after (very likely if copy/pasting values). `int.TryParse` could help you a great bit of the way. @CSharper has a usefull answer that explains the use of `int.TryParse`. – Heki Aug 31 '15 at 11:54

4 Answers4

3

if you don't know if the textbox is filled or contains not numerical value, try:

private void tbVerk6Breidd_KeyDown(object sender, KeyEventArgs e)
{
    int width;
    int.TryParse(tbTextBox.Text, out width )

}

if the text input is not a convertible integer you will retrieve 0

ale
  • 10,012
  • 5
  • 40
  • 49
1

Convert.ToInt32(tbTextBox.Text) can throw two type of exception.

1. FormatException // let say tbTextBox.Text = "abcdefghijkl";
2. OverflowException // let say tbTextBox.Text = "12345890690123456789012345997890";

so check what parameter do you have in tbTextBox.Text.

Solution: As mentioned above use 'TryParse' method of int.

Further read : -https://unwrapdotnet.wordpress.com/2014/01/14/all-about-int32-parse-convert-toint32-int32-tryparse/

Mukund
  • 1,679
  • 1
  • 11
  • 20
1

The Convert.ToInt32 methods throws two possible exceptions:

FormatException

value does not consist of an optional sign followed by a sequence of digits (0 through 9).

OverflowException

value represents a number that is less than Int32.MinValue or greater than Int32.MaxValue.

I guess you get a FormatException because the string within the textbox does not represent a valid int.

In your question you wrote ...the code is meant to execute when user presses a button, here is the code.. But you event handler is registred for a KeyDown event? If you want to check when ever the text within the text box changes (regardless of by copy paste or keyboard interaction) I recommend to use the TextChanged event of the textbox.

    private void tbVerk6Breidd_TextChanged(object sender, EventArgs e)
    {
        int parsed;
        if (int.TryParse(tbTextBox.Text, out parsed))
        {
            // parsed successfully
        }
        else
        {
            // invalid value
        }
    }
CodeTherapist
  • 2,776
  • 14
  • 24
0
try
{
   int width = int.Parse( tbTextBox.Text);     
   // do what you want to do
}
catch
{
   // do nothing, log?, display an error message ( that would probably be annoying )
}

You might also want to use a numeric up down control.

https://msdn.microsoft.com/en-us/library/system.windows.forms.numericupdown(v=vs.110).aspx

I don't know if you want to differentiate between the user actually entering "0", which is a valid input, and the case where they entered invalid data like "abasr4ra".

Derek
  • 7,615
  • 5
  • 33
  • 58