views:

130

answers:

3

Hi!

I inherited KryptonToolkit ListBox control to get SelectedItemChanging event.

public class CPListBox : KryptonListBox
{  
 public event CancelEventHandler SelectedIndexChanging;

 protected virtual void OnSelectedIndexChanging(CancelEventArgs e)
 {
  SelectedIndexChanging(this, e);
 }

 protected override void OnSelectedIndexChanged(EventArgs e)
 {   
  CancelEventArgs cArgs = new CancelEventArgs();
  OnSelectedIndexChanged(cArgs);

  if(!cArgs.Cancel)
  {
   base.OnSelectedIndexChanged(e);
  }
 }
}

In form I handle event with code:

    void UsersListBoxSelectedIndexChanging(object sender, CancelEventArgs e)
 {
  if(_presenter.CurrentUser.IsModified)
  {
   MessageBox.Show("Nie zapisales zmian!");
   e.Cancel = true;
  }

 }

And I got stackOverflow ;) Exception. Maybe someone now what is wron with this code?

+5  A: 

You're recursively calling the method in itself forever. There's no terminating condition for these recursive calls. It'll result in Stack Overflow.

protected override void OnSelectedIndexChanged(EventArgs e)
{                       
       CancelEventArgs cArgs = new CancelEventArgs();
       OnSelectedIndexChanged(cArgs); // Clearly calling yourself indefinitely.
       //...
}
Mehrdad Afshari
thanks ;) don't know how can i missed it ;)
Adrian Serafin
+2  A: 

You have OnSelectedIndexChanged call within OnSelectedIndexChanged, it's an endless recursive call.

o.k.w
+3  A: 
protected override void OnSelectedIndexChanged(EventArgs e)
        {                       
                CancelEventArgs cArgs = new CancelEventArgs();
                //Next line!!
                OnSelectedIndexChanged(cArgs);

                if(!cArgs.Cancel)
                {
                        base.OnSelectedIndexChanged(e);
                }
        }

You're calling yourself. Hence the StackOVerflow exception.

Yann Schwartz