Junelilly
Junelilly

Reputation: 394

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.

Upvotes: 0

Views: 634

Answers (1)

Chad McGrath
Chad McGrath

Reputation: 1601

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.

Upvotes: 3

Related Questions