Search code examples
c#uwpfocus

How to validate value entered into a textbox and prevent switching to another control?


I'm working on a uwp desktop application that must validate values entered in textboxes so that they are of type double. If they are not, the focus must remain on the current control. I tried the code below.

private async void tbxValue_LosingFocus(UIElement sender, LosingFocusEventArgs args)
    {
        try
        {
            double dbl = Convert.ToDouble(tbxValue.Text);
        }
        catch (Exception ex)
        {
            args.Cancel = true;
        
            MessageDialog msgDlg = new MessageDialog(resourceLoader.GetString("MsgDlgValueError"));
            await msgDlg.ShowAsync();

        }
    }

EDIT

I found a solution thanks to Flydog57's comments.

private async void myTextBox_LosingFocus(UIElement sender, LosingFocusEventArgs args)
    {
        if(!double.TryParse(((TextBox)sender).Text, out double dbl))
        {
            bool bolCancel = args.TryCancel();

            if(bolCancel)
            {
                MessageDialog msgDlg = new MessageDialog(resourceLoader.GetString("MsgDlgValueError"));
                await msgDlg.ShowAsync();
            }
        }
    }

Solution

  • I found a solution thanks to @Flydog57's comments.

    In this approach, I use the LosingFocus event to test whether the text typed in my TextBox corresponds to a double type number, using the double.TryParse method. If the value is not valid, I keep the focus on the TextBox and display a message to the user.

    private async void myTextBox_LosingFocus(UIElement sender, LosingFocusEventArgs args)
    {
        if(!double.TryParse(((TextBox)sender).Text, out double dbl))
        {
            bool bolCancel = args.TryCancel();
    
            if(bolCancel)
            {
                MessageDialog msgDlg = new MessageDialog(resourceLoader.GetString("MsgDlgValueError"));
                await msgDlg.ShowAsync();
            }
        }
    }