The textbox should only accept numbers and one .
value.
However, with my code, the input of numbers is also rejected as soon as I put a dot. I don't understand why, because in the if loop I do a check if the char I entered is a dot.
private void TextBox_BeforeTextChanging(TextBox sender, TextBoxBeforeTextChangingEventArgs args)
{
args.Cancel = args.NewText.Any(c => !char.IsDigit(c) && ".".IndexOf(c) != 0);
if (args.NewText.Any(c => c == '.' && sender.Text.IndexOf('.') > -1))
{
args.Cancel = true;
}
}
CodePudding user response:
As far as I understand the documentation, the NewText property is the text after you have typed in the next character - so if the sender TextBox contains "12." & you type a 3, then NewText will be "12.3".
I am similarly confused by your first check - but in your second check you are checking the current state of the sender TextBox (which already has the the dot in it) and also the new modified string - which also has the dot in it - resulting in you setting Cancel to true.
The only string you should be checking is NewText - you need to modify the checks to make sure the string only contains digits & one dot. Something like this would work :
args.Cancel = args.NewText.Any(c => !char.IsDigit(c) && c != '.');
if ( args.NewText.Where( c => c == '.').Count() > 1 )
args.Cancel = true;
There first line checks the string is only digits & dots, the second line checks for a single dot.
A single line solution would be to use a Regex - such as
args.Cancel = Regex.Match(args.NewText, @"^\d*\.?\d*$").Success;