#634 – Modifying Text in the TextChanged Event

Text-based controls like TextBox fire the TextChanged to indicate that their text has changed.  You can use this event to make changes to text being entered by the user, for example to convert all vowels in the TextBox to their uppercase equivalents.  This is possible because you can just set the Text property of a TextBox control from within the event.

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            Trace.WriteLine(string.Format("=>TextBox_TextChanged, now {0}", ((TextBox)sender).Text));
            TextBox tb = (TextBox)sender;

            // Preserve caret position so that we can later restore it
            int pos = tb.CaretIndex;

            tb.Text = CapVowels(tb.Text);

            tb.CaretIndex = pos;
        }

        private string CapVowels(string input)
        {
            const string vowels = "aeiou";

            StringBuilder sbInput = new StringBuilder(input);
            for (int i = 0; i < sbInput.Length; i++)
            {
                if (vowels.Contains(char.ToLowerInvariant(sbInput[i])))
                    sbInput[i] = char.ToUpper(sbInput[i]);
            }

            return sbInput.ToString();
        }

About these ads

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

3 Responses to #634 – Modifying Text in the TextChanged Event

  1. Pingback: Dew Drop – August 28, 2012 (#1,390) | Alvin Ashcraft's Morning Dew

  2. Mark Kestenbaum says:

    Won’t changing the Text property cause the event to fire again and eventually result in a stack overflow?

    • Sean says:

      Mark, yes this technique could lead to stack overflow, if the recursion never terminates because you continue making changes. For this particular case, the recursion terminates after we capitalize everything, e.g.:
      - User types “a”
      - TextChanged fires
      - We change text to “A”
      - TextChanged fires again
      - Vowels (“A”) already capitalized, so we don’t make any further changes and the recursion terminates

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 377 other followers

%d bloggers like this: