c#,listbox,stackOverflow异常

时间:2009-12-02 10:45:53

标签: c# winforms listbox selecteditemchanged

我继承了KryptonToolkit ListBox控件以获取SelectedItemChanging事件。

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);
        }
    }
}

在表单中,我使用代码处理事件:

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

    }

我得到stackOverflow;)例外。也许有人现在这个代码是什么wron?

3 个答案:

答案 0 :(得分:6)

您将永远以递归方式调用该方法。这些递归调用没有终止条件。它会导致Stack Overflow。

protected override void OnSelectedIndexChanged(EventArgs e)
{                       
       CancelEventArgs cArgs = new CancelEventArgs();
       OnSelectedIndexChanged(cArgs); // Clearly calling yourself indefinitely.
       //...
}

答案 1 :(得分:3)

protected override void OnSelectedIndexChanged(EventArgs e)
        {                       
                CancelEventArgs cArgs = new CancelEventArgs();
                //Next line!!
                OnSelectedIndexChanged(cArgs);

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

你在称自己。因此StackOVerflow异常。

答案 2 :(得分:2)

您在OnSelectedIndexChanged内有OnSelectedIndexChanged次来电,这是一次无休止的递归通话。