【问题标题】:ComboBox SelectedItem changes when BindingSource modified修改 BindingSource 时 ComboBox SelectedItem 发生变化
【发布时间】:2013-12-02 09:19:27
【问题描述】:

我的类管理器中有一个方法,它在我的后台工作人员完成并更新 BindingList (_suppliers) 时运行,它看起来像这样:

private void _bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        _suppliers.Clear();
        foreach (Classes.Supplier s in (BindingList<Classes.Supplier>)e.Result)
            _suppliers.Add(s);
    }

    public BindingSource BindingSource
    {
        get
        {
            if (_suppliers == null)
            {
                _suppliers = new BindingList<Classes.Supplier>();
            }

            return new BindingSource(_suppliers, null);
        }
    }

(我使用 .Clear() 然后循环使用 .Add() 的原因是因为如果我使用 _suppliers = new BindingList&lt;Classes.Supplier&gt;(func.LoadSuppliers()); BindingList 永远不会更新绑定控件...我不喜欢它)

我的问题是,当 _suppliers 被修改时,它会更改我所有与之关联的组合框中的选择,这是不想要的。

我像这样绑定我的组合框:

public BindingSource BindingSource
    {
        get
        {
            if (_suppliers == null)
            {
                _suppliers = new BindingList<Classes.Supplier>();
            }

            return new BindingSource(_suppliers, null);
        }
    }

我这样修改它们:

public bool Add(Classes.Supplier supplier)
    {
        if (_suppliers == null)
        {
            _suppliers = new BindingList<Classes.Supplier>();
        }

        using (SQLiteFunction func = new SQLiteFunction())
        {
            try
            {
                if (func.AddSupplier(supplier))
                    _suppliers.Add(supplier);
            }
            catch (Exception ex)
            {
                Helper.ExceptionHandler(ex, "SupplierManager", "Add");
                return false;
            }
        }

        return true;
    }

有人对如何绕过这个有任何想法吗?设置.SelectedIndex = -1 或类似的东西是不想要的,因为如果用户选择了列表中的一个项目,我希望选择保留......如果可能的话。

一如既往地为所有帮助和 cmets 提供帮助。

【问题讨论】:

    标签: c# winforms combobox bindingsource bindinglist


    【解决方案1】:

    这是预期的行为。 您正在回调 _bw_RunWorkerCompleted 期间删除数据源“_suppliers.clear()”的内容。所以之后就没有选中项了。

    要绕过这个,请记住选定的项目并在重新创建列表后分配它。 也许你必须实现 selchange 事件处理程序不会被触发。

    【讨论】:

    • 感谢您的回复@TomB。由于我有多个使用此 BindingSource() 作为数据源的组合框,因此我可以有多个 .selectedItems()。有没有一种方法可以让我从经理类中跟踪所有这些?
    • @Webslave。我想我已经看到同步触发的事件(例如,如果您在绑定到 ADO.NET 中的共享源的组合框上执行 selchange)。但我还没有看透数据绑定中的所有魔力。一个实用的解决方案是创建一个组合框数组,遍历它们并记住选定的项目
    猜你喜欢
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    相关资源
    最近更新 更多