如何在下拉列表中访问选定的索引更改?

时间:2014-01-08 17:57:51

标签: c# user-controls

我是C#的新手,我创建了一个类似于此线程中的人的用户控件:

add user control to a form

只有,我用了4个下拉菜单。我创建了一个自定义用户控件,其类名为CustomBaseUserControl.cs。它为每个下拉列表提供了所有选定的索引更改事件。从表单中,将其命名为TheFormControl,将CustomBaseUserControl放入其中,如何访问这些事件更改值?

提前致谢!

1 个答案:

答案 0 :(得分:1)

如果您需要在TheFormControl上检索选定的索引,则可以

使用变量将值存储在CustomBaseUserControl上,在这种情况下,您必须侦听SelectedIndexChanged事件并更新您的值。

触发从CustomBaseUserControl更改为TheFormControl

的自定义选定索引

-

class CustomBaseUserControl: UserControl{
int idx1=-1;
public CustomBaseUserControl()
{
    Initialize();
    //Fill ComboBox

    //Suscribe Event
    combobox1.SelectedIndexChanged += combobox1_SelectedIndexChanged;
}
  void combobox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int index = combobox1.SelectedIndex;
        if (index != idx1)
        {
        idx1=index;
        RaiseIndexChanged(e);
        }

    }

        public virtual void RaiseIndexChanged(EventArgs ea)
    {
        var handler = OnIndexChanged;
        if (OnIndexChanged != null)
            OnIndexChanged(this, ea);
    }
    public event EventHandler OnIndexChanged;
}  

来电者课程将是

class TheFormControl: Form
{
    CustomBaseUserControl cb;
    public TheFormControl()
    {
        Initialize();
        cb = new CustomBaseUserControl();
        cb.OnIndexChanged +=cb_OnIndexChanged;
    }
    void cb_OnIndexChanged(object sender, EventArgs e)
    {
     // Here you know index has changed on CustomBaseUserControl
    }
}