-2

I quickly made a Windows Forms project which loads a GUI of different textboxes with float values. Some of them do have already a value initialized. All textboxes have to be updated after one of them is changed.

public Form1()
{
    InitializeComponent();
    initializeValues();
    calculateValues();
}

public void initializeValues()
{
//textboxes are filled/initialized with default float values
}

public void calculateValues()
{
//here all textboxes are new calculated and updated
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    calculateValues();
}

private void textBox2_TextChanged(object sender, EventArgs e)
{
    calculateValues();
}

Problem: When I execute this project, it throws me a StackOverflowException which is unhandeled (infinite loop or infinite recursion). I think it's because during the calculateValues() method the text of the textBoxes will be changed and then the Eventhandlers are activated. That's the infinite loop :-(

How I have to change my code construct above to avoid this?

Thanks.

Kevin
  • 229
  • 2
  • 10
  • 19
  • 1
    Set breakpoints, step through your code and you will find that your suspicions are correct. Simply unsubscribe the event before, and resubscribe after the change. – CodeCaster May 13 '16 at 09:37
  • Set your IDE to break, when a Win32 exception is thrown. You'll have the entire callstack right there in front of you, instantly giving away, why you have an infinite loop/infinite recursion. – IInspectable May 13 '16 at 09:48

2 Answers2

0

You should not using and calling "initializeValues();" (the cause of the infinite loop).

A first solution could be to put the init value of a TextBox in InitializeComponent :

MyTextBox.Text = myInitValue;

Benoît
  • 87
  • 8
  • Why would a regular, non-recursive function call cause a stackoverflow or an infinite loop? You are jumping to conclusions too easily. – IInspectable May 13 '16 at 09:47
0

I solved the problem by changing the Event to "KeyPress". In this case, the Event is not activated by the method itself. No more infinite loops. Setting breakpoints and step through helped me to understand "the flow". Thanks CodeCaster.

Kevin
  • 229
  • 2
  • 10
  • 19