Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Only allow numbers and a Minus "-" in a Textbox

Tags:

c#

wpf

I would like to know how I would be able to allow only numbers and a "-" minus sign in a textbox?

Here is coding that I can already allow only numbers:

private void txtDicountSettlement_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex("[^0-9]+");
    e.Handled = regex.IsMatch(e.Text);
}
like image 361
CareTaker22 Avatar asked Jul 28 '15 12:07

CareTaker22


1 Answers

Just add the - to your regex character group, in a position that's not making a range of characters:

private void txtDicountSettlement_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex("[^0-9-]+");
    e.Handled = regex.IsMatch(e.Text);
}
like image 132
James Thorpe Avatar answered Oct 03 '22 05:10

James Thorpe