How can I handle ComboBox selected index changing?

前端 未结 10 1271
花落未央
花落未央 2020-12-21 06:10

I have a ComboBox that have a list of manufacturers. When a user selects a manufacturer, a grid below is populated with data for the chosen manufacturer. That data can be mo

10条回答
  •  忘掉有多难
    2020-12-21 06:49

    Night Coder's solution is elegant and concise. I have packaged it in a dll.
    (I call it CustomControls.) To do this create a new class library and add the first few statements to Night Coder's solution (copied here as a convenience).

    Once you have compiled the code, you can add it as a reference. I actually loaded the dll into my Visual Studio Tools pane. That way I can drag the control onto my form at design time. Conveniently, the new event shows up in the properties list.

    use System.ComponentModel;
    
    use System.Windows.Forms; //this will need to be added as a reference
    
    //your namespace will name your dll call it what you will
    
    namespace CustomControls
    

    Night Coder's solution follows:

    public class ComboBoxEx : ComboBox
    {
            public event CancelEventHandler SelectedIndexChanging;
    
    
        [Browsable(false)]
        public int LastAcceptedSelectedIndex { get; private set; }
    
        public ComboBoxEx()
        {
                LastAcceptedSelectedIndex = -1;
        }
    
        protected void OnSelectedIndexChanging(CancelEventArgs e)
        {
                var selectedIndexChanging = SelectedIndexChanging;
                if (selectedIndexChanging != null)
                        selectedIndexChanging(this, e);
        }
    
    
        protected override void OnSelectedIndexChanged(EventArgs e)
        {
                if (LastAcceptedSelectedIndex != SelectedIndex)
                {
                        var cancelEventArgs = new CancelEventArgs();
                        OnSelectedIndexChanging(cancelEventArgs);
    
                        if (!cancelEventArgs.Cancel)
                        {
                                LastAcceptedSelectedIndex = SelectedIndex;
                                base.OnSelectedIndexChanged(e);
                        }
                        else
                                SelectedIndex = LastAcceptedSelectedIndex;
                }
        }
    }
    

提交回复
热议问题