#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();