Search code examples
c#-4.0windows-phone-8

Windows phone:Do not allow more than one dot in a textbox?


I am writing application in windows phone 8.

I need to provide a textbox which will allow user to enter only "Numbers" and if required, only one dot ".

I set <TextBox InputScope="Number" /> but it allow multiple dot.

How can i set single dot in textbox of windows phone?


Solution

  • Set an event that triggers everytime a text has change like this:

     <TextBox x:Name="textBox1" TextChanged="textBox1_TextChanged" />
    

    And then in the event function loop through the text, count the dots and if the dot count is higher than 1, delete the said dot.

    EDIT: you said if I could provide a sample algorithm:

            string str = textBox1.Text;
            int dotCount = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == '.')
                {
                    dotCount++;
                    if (dotCount > 1)
                    {
                        str.Remove(i, 1);
                        i--;
                        dotCount--;
                    }
                }
            }