Convert TextBox.Text to Int32 Problem
<chris.stueck@centerpointenergy.com> wrote:
[color=blue]
> Need a little help here. I saw some related posts, so here goes... I
> have some textboxes which are designed for the user to enter a
> integer value. In "old school C" we just used the atoi function and
> there you have it. So I enquired and found the Convert class with
> it's promising ToInt32 method, great... but it doesn't work. The
> thing keeps throwing Format Exceptions all over the place. What is
> the "C#" way to do this??? code:
>
> int wmin, wsec, x;
> int hrs, min, sec, miles;
> miles = Convert.ToInt32(txtMiles.text);
> hrs = Convert.ToInt32(txtHours.text);
> min = Convert.ToInt32(txtMinutes.text);
> sec = Convert.ToInt32(txtSeconds.text);
> . . .[/color]
If Convert.ToInt32(string) is throwing an exception, then your text
presumably isn't a valid integer. Note that unlike atoi, which stops
when it meets the first non-numeric character and returns whatever it's
parsed so far, Convert.ToInt32(string) and Int32.Parse both require the
whole string to be a valid integer value (although whitespace is
allowed, by default).
If you want to emulate atoi, you'll have to write a method to find the
leading substring of a string which is composed of digits (perhaps
prefixed with '-'), or "0" if such a string would have no digits in.
[color=blue]
> I even tried forcing the values to string by using .... miles =
> Convert.ToInt32(txtMiles.text.ToString());[/color]
If it wasn't a string before, what was it? I would imagine it was
already a string - calling ToString() on a string isn't going to make
any difference.
--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too