Monday, October 8, 2012

Entering only Numeric

Entering only Numeric

Hi,

How can I enter only numeric value in a TextBox  with Del and Back space  but not Alphabets and Special Characters.

 

Regards,

 

Answers & Comments...

Answer: 1

Hi, according to your requirement, I suggest you to use NumericUpDown control from Silverlight Toolkit instead of normal TextBox. Or you can use below code to achieve it:

<TextBox Name="Just4Testing" Width="100" TextChanged="Just4Testing_TextChanged"></TextBox>  
        private void Just4Testing_TextChanged(object sender, TextChangedEventArgs e)          {              String OriginalValue = Just4Testing.Text.Trim();              int IntValue;              if (OriginalValue.Length > 0 && !int.TryParse(OriginalValue, out IntValue))              {                  Just4Testing.Text = OriginalValue.Substring(0, OriginalValue.Length - 1);              }          }

Best Regards,



Answer: 2

hi suresh, try this on Key down event of your TextBox:

if (((e.Key > Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Back || e.Key == Key.Tab))

e.Handled = false;

else

{

e.Handled = true;

}

This works fine for me. [:)]



Answer: 3

sureshsahu

sureshsahu

public class CurrencyTextBox : TriggerAction<DependencyObject>      {          protected override void Invoke(object parameter)          {              TextBox tb = this.AssociatedObject as TextBox;              tb.KeyDown += new KeyEventHandler(RaiseKeyDownEvent);          }            private void RaiseKeyDownEvent(object sender, KeyEventArgs e)          {              if (sender == null) return;              Regex regex = new Regex("^[0-9]+$");              if (regex.IsMatch(e.Key.ToString().Substring(e.Key.ToString().Length - 1, 1)) || e.Key == Key.Decimal || e.Key == Key.Unknown)                  e.Handled = false;              else                  e.Handled = true;          }      }  

 

 

Just tweak up some of the code. Hope you find it help.





No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog