1

I am trying to add a space after the 3rd or 4th character in a text box depending on the total characters.

For example If the text box value contains 6 characters, then add a space after the 3rd character. If the text box value contains 7 characters, then add a space after the 4th character.

Example for 7 Characters in a text box

Before Lost Focus

Lost Focus

Example for 6 Characters in a text box

Before Lost Focus

Lost Focus

Where I am currently at with trying to get this to work.

private void FirstPostcode_LostFocus(object sender, RoutedEventArgs e)
    {
        if (FirstPostcode.Text.Length == 3)
        {
            FirstPostcode.Text += " ";
        }
    }

Any help would be appreciated. Thanks.

  • 1
    Your code seems to be designed for `TextChanged` event. While typing it will add space once after 3 characters are there. For `LostFocus` or enter key press you have to insert space. You could use [masked textbox](https://stackoverflow.com/q/481059/1997232) instead. – Sinatr Apr 09 '19 at 10:15
  • Why are you checking if string's length is `3`, when in your question you are asking about lengths `6` and `7`? – SᴇM Apr 09 '19 at 10:18
  • You'd do better to format the postcode on leaving the box, what do you plan to do for postcodes like "B1 1AA" ? as the one constant is the last 3 digits. – BugFinder Apr 09 '19 at 10:20
  • do you wana do in `mvvm`? – Avinash Reddy Apr 09 '19 at 10:20
  • @BugFinder I didn't notice it was 3 and I am using it for physical properties so I wouldn't ever use postcodes like "B1 1AA". – Java2YourScript Apr 09 '19 at 10:35

2 Answers2

2

You can use Insert() to insert a space at the third position from the right.

if (FirstPostcode.Text >= 3)
{
    FirstPostcode.Text = FirstPostcode.Text.Insert(FirstPostcode.Text.Length - 3, " ");
}

If you want to check first if the space was already inserted and don't want to insert it again you could use the indexer on the string.

if (FirstPostcode.Text.Length == 3 
     || FirstPostcode.Text.Length >= 4
        && FirstPostcode.Text[FirstPostcode.Text.Length - 4] != ' ')
{
    FirstPostcode.Text = FirstPostcode.Text.Insert(FirstPostcode.Text.Length - 3, " ");
}
sticky bit
  • 36,626
  • 12
  • 31
  • 42
0

Try following :

            string[] inputs = { "NR105BE", "BD11AA" };

            foreach (string input in inputs)
            {
                string output = "";
                if (input.Length == 7)
                {
                    output = input.Substring(0, 4) + " " + input.Substring(4);
                }
                else
                {
                    output = input.Substring(0, 3) + " " + input.Substring(3);
                }
                Console.WriteLine(output);
            }
            Console.ReadLine();
jdweng
  • 33,250
  • 2
  • 15
  • 20