#634 – Modifying Text in the TextChanged Event
August 28, 2012 3 Comments
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(); }
Pingback: Dew Drop – August 28, 2012 (#1,390) | Alvin Ashcraft's Morning Dew
Won’t changing the Text property cause the event to fire again and eventually result in a stack overflow?
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