Is it possible to recognize two commas entered into TextBox?

VoyTec 671 Reputation points

I am asking for a code that will recognize two commas in one TextBox, so I can use double.Parse with no errors, cleaning one comma.

Universal Windows Platform (UWP)
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,170 questions
{count} votes

Accepted answer
  1. Roy Li - MSFT 31,551 Reputation points Microsoft Vendor


    Welcome to Microsoft Q&A!

    I'm not sure about the input data that you mentioned. But I have made a solution about how to clean the second comma when user type something in the TextBox. We could handle the TextBox.TextChanged Event and check the input value when user input every character. Then if we find that there are two commas, remove the last comma.

    Here is the code I use:

            private void MyTextBox_TextChanged(object sender, TextChangedEventArgs e)
                //remove the second comma
                TextBox textBox = sender as TextBox;
                string inputString = textBox.Text;
                int count = Regex.Matches(inputString, ",").Count;
                if (count > 1)
                    var lastIndex = inputString.LastIndexOf(",");
                    inputString= inputString.Remove(lastIndex, 1);
                textBox.Text = inputString;
                textBox.SelectionStart = textBox.Text.Length;
                textBox.SelectionLength = 0;
                var d = double.Parse(textBox.Text);

    Thank you.

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce ( 54,621 Reputation points

    so are commas for 100, 1000, etc separator, or for whole and decimal?

    if the former its just:

    value = value.Replace(",","")

    if the latter, how do you know which one is correct?