如何在c#中防止/取消组合框的值变化?

22 c# combobox winforms

我在表单顶部有一个组合框,可将可编辑数据加载到下面的字段中.如果用户进行了更改但未保存,并尝试从组合框中选择其他选项,我想警告他们并给他们取消或保存的机会.

我需要一个带有可取消事件参数的"BeforeValueChange"事件.

有关如何完成的任何建议?

Den*_*dic 16

如果首次输入,请将ComboBox的SelectedIndex保存到框中,然后在需要取消更改时恢复其值.

cbx_Example.Enter += cbx_Example_Enter;
cbx_Example.SelectionChangeCommitted += cbx_Example_SelectionChangeCommitted;

...

private int prevExampleIndex = 0;
private void cbx_Example_Enter(object sender, EventArgs e)
{
    prevExampleIndex = cbx_Example.SelectedIndex;
}

private void cbx_Example_SelectionChangeCommitted(object sender, EventArgs e)
{
    // some custom flag to determine Edit mode
    if (mode == FormModes.EDIT) 
    {
        cbx_Example.SelectedIndex = prevExampleIndex;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不需要使用"Enter"事件来保存最后的选择.在退出`SelectionChangeCommitted`事件处理程序之前,只需将`lastSelectedIndex`值保存为`private`变量.此后,进入该事件处理程序的后续条目可以使用`lastSelectedIndex`将`ComboBox.SelectedIndex`设置为前一个位置. (2认同)

Kus*_*kar 8

这是最简单的修复:-

        bool isSelectionHandled = true;

        void CmbBx_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (isSelectionHandled)
            {
                MessageBoxResult result = MessageBox.Show("Do you wish to continue selection change?", this.Title, MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.No)
                {
                    ComboBox combo = (ComboBox)sender;
                    isSelectionHandled = false;
                    if (e.RemovedItems.Count > 0)
                        combo.SelectedItem = e.RemovedItems[0];
                    return;
                }
            }
            isSelectionHandled = true;
        }
Run Code Online (Sandbox Code Playgroud)


Sim*_*mon 0

您可以使用消息过滤器来拦截点击和按键,这将允许您阻止组合框的正常行为。但我认为您最好在用户进行更改时禁用组合框,并要求他们保存或恢复更改。