-1

Good evening,

trying to make WPF textbox accept only double value between 3 and 2813

in the code below ,I can't write any value start with 1 or 2

like 11,22,113,215,2008

private bool IsValid(string str)
{
    double i;
    return double.TryParse(str, out i) && i >= 3 && i <= 2813;
}

private void L_Text_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = !IsValid(((TextBox)sender).Text + e.Text);
}
Max Play
  • 3,717
  • 1
  • 22
  • 39
Almutaz
  • 11
  • 4
  • Have you tried breaking the return statement of IsValid up into multiple statements and check the actual value of i and the str? Have you made sure that the input can be parsed to a double correctly? – Max Play Jun 04 '21 at 18:11

2 Answers2

1

PreviewTextInput occurs whenever the user presses a key. So we can't know whether the user intends to write "2" or "22" at this moment. To evaluate the value we must be sure that the user finished writing. You can use LostFocus event for this purpose.

private bool IsValid(string str)
{
    double i;         
    return double.TryParse(str, out i) && i >= 3 && i <= 2813;
}
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
    var txt = sender as TextBox;
    if (!IsValid((txt.Text)))
    {
        //invalid delete text
        txt.Text = "";
    }
} 

Detailed validation: https://stackoverflow.com/a/37255232/1431001

aliassce
  • 1,197
  • 6
  • 19
0

There are 2 things you could do

  1. You could evaluate if it starts with a specific character, and then parse that
  2. You could use https://help.syncfusion.com/wpf/double-textbox/getting-started