0

Possible Duplicate:
Create WPF TextBox that accepts only numbers

How i can check if inputed value in textbox contains text? I want to user input only numbers Thanks

Community
  • 1
  • 1
Irakli Lekishvili
  • 32,032
  • 33
  • 109
  • 169

3 Answers3

5

Assuming you are using integers then:

int value = 0;
if(!Int32.TryParse(strInput, out value))
{
    // Validation failed - show error or feedback to user
}
else
{
    // Validation successful
}

For doubles, replace Int32.TryParse with Double.TryParse etc.

There is probably some fancy WPF way to do this as well (as indicated by V4Vendetta's comment).

mdm
  • 12,230
  • 5
  • 33
  • 53
  • +1 for TryParse rather than Parse - you don't want to be throwing exceptions if you're expecting things not to parse correctly sometimes. – Shaul Behr Jul 18 '11 at 11:10
  • Thanks so much. Can you help me again? I want to allow numbers and . (dot) how i can do that? – Irakli Lekishvili Jul 18 '11 at 13:15
  • Well, the example I posted is for Integers. You could try using `Double.TryParse` instead of `Int32.TryParse` - a 'double' allows you to have decimal places, so it will allow numbers like `5.5` as well as just `5`. Hope it helps :) – mdm Jul 18 '11 at 13:44
2

You could you a regular expression to check for @"[^\d]" if true there are non numbers

Alternatively @"^\d+$" will match ints and @"\d+(\.\d+)?$" will match decimals

Alternatively you could use a maskedtextbox control, either by embeding the winforms control using a host control or using something like Infragistics editor.

Bob Vale
  • 17,579
  • 40
  • 48
1

If you want only number check if you can parse it. If you want int use int.Parse()

H.B.
  • 142,212
  • 27
  • 297
  • 366
Piotr Auguscik
  • 3,591
  • 1
  • 21
  • 28