【问题标题】:How to cancel a combobox's value change in c#?如何在c#中取消组合框的值更改?
【发布时间】:2015-07-04 17:13:56
【问题描述】:

我有一个组合框。

如果用户进行了更改但未保存,并尝试从组合框中选择不同的选项,则消息框会警告他们并给他们机会

1 取消(保留更改)

2 否(放弃更改)

3 是(保存费用)

例如:

组合框包含的值

电脑

笔记本电脑

电话

电视

相机

用户选择了“相机”,然后将其更改为“相机78778” 然后用户从组合框中选择了另一个值(比如 "Computer" )

消息框警告他们并给他们机会

1 取消(保留更改):组合框为“Camera78778”

2 否(放弃更改):组合框是“计算机”

3 是(保存更改):组合框是“计算机”,但此处更改已保存。

我需要取消的代码。

我试过 comboBox1.SelectedIndexChanged -= comboBox1._SelectedIndexChanged; 但没有解决办法。 我尝试了 comboBox1_SelectionChangeCommitted 但没有解决方案。

感谢高级。

更新

    int lastIndexcomboBox1 = -1;

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
    Myfunction(comboBox1.SelectedIndex);
    }

    private void Myfunction(int comboBox1SelectedIndex)
    {

        if(comboBox1.Tag.ToString() == "not changed")
        {

        }
        else
        {
            DialogResult dr = MessageBox.Show("Do you want to save", "", MessageBoxButtons.YesNoCancel);
            if (dr == DialogResult.Yes)
            {

            }
            else if (dr == DialogResult.No)
            {

            }
            else if (dr == DialogResult.Cancel)
            {
                comboBox1.SelectedIndexChanged -= comboBox1_SelectedIndexChanged;
                comboBox1.SelectedIndex = lastIndexcomboBox1;
                comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
            }
        }

    }

【问题讨论】:

标签: c# winforms combobox


【解决方案1】:

您可以将当前所选索引的信息保存在私有变量中,并执行以下操作:

private int _comboBoxIndex = -1;
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    var dialogResult = MessageBox.Show("Confirm your action", "Info", MessageBoxButtons.YesNoCancel);

    switch (dialogResult)
    {
        // Detach event just to avoid popping message box again
        case DialogResult.Cancel: 
            comboBox.SelectedIndexChanged -= comboBox_SelectedIndexChanged;
            comboBox.SelectedIndex = _comboBoxIndex;
            comboBox.SelectedIndexChanged += comboBox_SelectedIndexChanged;
            break;
        case DialogResult.No:
            // Do something
            _comboBoxIndex = comboBox.SelectedIndex;
            break;
        case DialogResult.Yes:
            // Do something
            _comboBoxIndex = comboBox.SelectedIndex;
            break;
    }
}

【讨论】:

  • 我尝试了这段代码,但我对组合框值的更改已经消失
  • @mukhtarghaleb 你能发布你的代码吗?我不确定是什么困扰着你。这在我的测试用例中运行良好。
猜你喜欢
  • 2010-09-23
  • 1970-01-01
  • 1970-01-01
  • 2019-06-21
  • 2020-04-22
  • 1970-01-01
  • 2022-01-23
  • 2022-07-10
  • 1970-01-01
相关资源
最近更新 更多