Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

.net - How can I handle ComboBox selected index changing?

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 modified. The user has to press the Save button after all changes are done.

But the user can forget to press Save and select another manufacturer from the ComboBox and the grid will be populated with another data, so previous changes will be lost.

So I need to ask user if he wants to save changes before selecting another manufacturer.

How can I do this? Or maybe you offer another way of solving my task (looking from another angle)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is how we can subclass ComboBox to introduce new SelectedIndexChangingEvent with a possibility to cancel the changing:

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...