TextBox with only numbers

后端 未结 3 993
谎友^
谎友^ 2021-01-21 04:16

I need to create a TextBox with only numbers but I couldn\'t do. I have tried to put : InputScope = \"Numbers\" but this only work on Mobile. Also I have tried on TextCha

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-21 05:01

    You can either prevent any non-numeric input whatsoever, or just filter out digits in the text.

    Preventing non-digit input

    Use the BeforeTextChanging event:

    
    

    And now handle like this:

    private void TextBox_OnBeforeTextChanging(TextBox sender,
                                              TextBoxBeforeTextChangingEventArgs args)
    {
        args.Cancel = args.NewText.Any(c => !char.IsDigit(c));
    }
    

    This LINQ expression will return true and hence Cancel the text change in case it encounters any non-digit character in the input.

    Filtering non-digit input

    Use the TextChanging event:

     
    

    And handle this way:

    private void TextBox_OnTextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
    {
        sender.Text = new String(sender.Text.Where(char.IsDigit).ToArray());
    }
    

    This LINQ query will filter out non-digit characters and create a new string only with the digits in the input.

    It is preferable to use TextChanging and BeforeTextChanging, because TextChanged occurs too late, so the user would be confused by seeing characters temporarily display on the screen and immediately disappearing.

提交回复
热议问题