Is it possible to recognize two commas entered into TextBox?

VoyTec 671 Reputation points
2023-03-17T19:46:17.74+00:00

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)
C#
C#
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.
11,454 questions
{count} votes

Accepted answer
  1. Anonymous
    2023-03-22T10:12:40.2766667+00:00

    Hello,

    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);
                Debug.WriteLine(d);
            }
    
    

    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 (SqlWork.com) 75,386 Reputation points Moderator
    2023-03-17T19:55:34.12+00:00

    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?


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.