Search code examples
c#event-handlingstack-overflow

Event Handler triggers System.StackOverflowException


Code:

 private void addExcel(object sender, TextChangedEventArgs e)
 {
        if (!textBox.Text.Contains('!'))
        {
            textBox.Text += "!";
        }
        StringBuilder sb = new StringBuilder();
        sb.Append(textBox.Text);
        sb.Remove(textBox.Text.IndexOf('!'), 1);
        textBox.Text = sb.ToString();
 }

The exception occurs in sb.ToString(); This application is supposed to calculate factorials.


Solution

  • I assume that this is called in your TextBox.TextChanged event. When this happens :textBox.Text = sb.ToString(); It adds a string with no "!" to the textbox, which is then changed, which then triggers the event, which then:

    if (!textBox.Text.Contains('!'))
            {
                textBox.Text += "!";
            }
    

    adds a "!", which then triggers the event where it is removed again. FOREVAR!

    Your best bet is to assign sb.ToString() to another variable, other than textbox.