I have a textbox that I’m trying to limit in two ways:
1 – I only want to allow numeric values, no decimals
2 – I only want to accept numbers that are <= 35
I have the following events to handle this:
private void TextBoxWorkflowCountPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!IsNumeric(e.Text, NumberStyles.Integer)) e.Handled = true;
}
public bool IsNumeric(string val, NumberStyles numberStyle)
{
double result;
return double.TryParse(val, numberStyle, CultureInfo.CurrentCulture, out result);
}
private void TextBoxWorkflowCountTextChanged(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(textBoxWorkflowCount.Text) && Convert.ToInt32(textBoxWorkflowCount.Text) <= 35) e.Handled = true;
else
{
MessageBox.Show("Must not be higher then 35");
textBoxWorkflowCount.Text = "35";
}
}
This on the surface works perfectly fine – except when the user either pastes data into the textbox (appears unavoidable) or even more curiously – if the user enters a number and then hits backspace (making the textbox blank again) the messagebox letting the user know that their value is >35 appears (even though that is definitely not the case). The first issue I can live with if I have to – but the second is game breaking and after 30 minutes of trying to solve it I’ve got nowhere. Help!
Your code is failing the first condition because
evaluates to true, so it’s falling through to the ‘else’, and displaying the message.
should do the trick