UWP C# TextBox with numbers and "space" only.

VoyTec 671 Reputation points
2022-11-08T21:55:02.12+00:00

How can I create a TextBox that can only contain numbers and spacebar?

Developer technologies Universal Windows Platform (UWP)
0 comments No comments
{count} vote

Accepted answer
  1. Junjie Zhu - MSFT 21,646 Reputation points
    2022-11-09T02:28:46.333+00:00

    Hi @VoyTec ,

    This question is similar to your previous question, you just need to modify the regular expression ^[\\s\\d\\s]*$.

    Page.xaml

    <TextBox  TextChanged="TextBox_TextChanged" />  
    

    Page.xaml.cs

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)  
    {  
        var textbox = (TextBox)sender;  
        if (!Regex.IsMatch(textbox.Text, "^[\\s\\d\\s]*$") && textbox.Text != "")  
        {  
            int txtPos = textbox.SelectionStart - 1;  
            textbox.Text = textbox.Text.Remove(txtPos, 1);  
            textbox.SelectionStart = txtPos;  
        }       
    }  
    

    Thank you
    Junjie

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.