Integer value from a text box.

  • Thread starter Thread starter C# Learner
  • Start date Start date
C

C# Learner

I am working n 1.1 btw so i'll have to validate it.

It might be better UI design to only allow the user to enter a valid value,
using a KeyPress event handler such as:

void textBox_KeyPress(object sender, KeyPressEventArgs e) {
e.Handled = !(Char.IsDigit(e.KeyChar) || e.KeyChar == '\b');
}

Also, you'll have to take into account that the user could enter a value
that will be higher than an Int32 can hold. You could get around this by
setting textBox.MaxLength to some value (specifically, a value less than
Int32.MaxValue.ToString().Length, which is 10).

If this isn't desirable, you'd have to just catch the exception in the next
statement and handle it.
I will look at using the convert service on the text box class though.

Int32.Parse(textBox.Text).
 
Hi,
I'm a little new to C#, so bear with me. I have a text box on a form,
and I want to be able to get an integer value of whats in it.

In VC++ you just set the text box property to be numerals only, and then
call GetDlgItemInt(); and then it's plain sailing.

There must be an easy way in C#?

Cheers,

Rob.
 
Robert Wilson said:
I'm a little new to C#, so bear with me. I have a text box on a form,
and I want to be able to get an integer value of whats in it.

In VC++ you just set the text box property to be numerals only, and then
call GetDlgItemInt(); and then it's plain sailing.

There must be an easy way in C#?

Just use the same way you convert any other string value to an int -
Convert.ToInt32 or int.Parse.

I don't know if there's an easier way of making the text box "digits
only" than adding a keypress handler.
 
Robert,

In .NET 1.1, there is nothing out of the box that will allow you to do
this. However, you could hook up to the events on the textbox that monitor
when keys are pressed, and invalidate them if they don't form a number.

There should be a good number of examples of this already coded and
available on the web.

Also, in .NET 2.0, there is a MaskedTextBox which you can set a mask to
which will allow only certain types of input.

Hope this helps.
 
Thanks fellas. That's what I wanted to know. Here's to .Net 2.0 then.
I am working n 1.1 btw so i'll have to validate it. I will look at
using the convert service on the text box class though.

Thanks again,

Robert.
 
Hi,

I don't know if there's an easier way of making the text box "digits
only" than adding a keypress handler.

As far as I know there are two ways of doing this,
1- using KeyPress ( my preferred )
2- extending TextBox and overriden CreateParams

I don;t know if in 2.0 we will have this property as public ( now is
protected )

If you search in the NG you will probably find this functionality ready to
be used.

Cheers,
 
Back
Top