【问题标题】:Exception when swapping value from one listbox to another listbox将值从一个列表框交换到另一个列表框时出现异常
【发布时间】:2013-03-25 02:43:18
【问题描述】:

我有两个列表框。当我将值从一个列表框交换到另一个列表框时,我得到一个异常Items collection cannot be modified when the DataSource property is set. 我该如何解决它?

在我绑定列表框和交换值的代码下方

为了交换值,我使用这个:

 private void MoveListBoxItems(ListBox lstEmployeelist, ListBox lstSelectedEmployees)
    {

        ListBox.SelectedObjectCollection sourceItems = lstEmployeelist.SelectedItems;


        try
        {
            for (int i = 0; i <= sourceItems.Count - 1; i++ )
            {
                object item = sourceItems[i];

                lstSelectedEmployees.Items.Add(item);
                lstEmployeelist.Items.RemoveAt(i);

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }

对于绑定列表框,我使用此代码

if (_empComponent == null)
            _empComponent = new EmployeeComponent();
        lstEmployeelist.DataSource = _empComponent.GetEmpCodeWithName();
        lstEmployeelist.ValueMember = "Empno";
        lstEmployeelist.DisplayMember = "FirstName";

我该如何解决这个问题?

【问题讨论】:

    标签: c# winforms listbox datasource


    【解决方案1】:

    这很简单:当您使用 DataSource 时,您无法修改 Items 集合,因为这些项目是从数据源自动填充的。

    改为更改数据源,即_empComponent.GetEmpCodeWithName()后面的数据结构

    【讨论】:

    • 第一次加载页面时,我填写了所有员工表单,如果没有这个功能,lisbox 怎么能有一些值
    【解决方案2】:

    改为在数据源列表中进行更改 - 在分配之前将其保存在 sime provate 字段中,

    if (_empComponent == null)
        _empComponent = new EmployeeComponent();
    
    _myPrivateCollection = _empComponent.GetEmpCodeWithName();
    lstEmployeelist.DataSource = _myPrivateCollection;
    lstEmployeelist.ValueMember = "Empno";
    lstEmployeelist.DisplayMember = "FirstName";
    

    在需要时,更改并重新分配 DataSource:

    //I don't know your logic here, but probably there is a bug - you are modifying collection and then use old index position - you'll get unexpected results =). Let you fix it on your own, so just rewrite your code
    for (int i = 0; i <= lstEmployeelist.SelectedIndices.Count; i++ )
    {
        var index = lstEmployeelist.SelectedIndices[i]
        object item = _myPrivateCollection[index];
    
        _myPrivateCollection.Add(item);
        _myPrivateCollection.RemoveAt(index);
    }
    lstEmployeelist.DataSource = null;
    lstEmployeelist.DataSource = _myPrivateCollection;
    

    请注意,这种技术不应该经常用于非常大的列表,因为它运行缓慢。但这是满足您需求的最简单方法。

    【讨论】:

    • 编辑了我的答案 - 添加了更多代码。请注意对代码中的逻辑错误的评论
    • @Olesandr Pshenychnyy 感谢您的回复我在我的页面上使用 bindingsource 这工作正常,但我如何分配这些对绑定源有更改的值
    • BindingSource 本身具有 DataSource 属性。按照我描述的方式使用它
    • 好的,我面临的问题是_myPrivateCollection.Add(item); _myPrivateCollection.RemoveAt(index); 在这里我得到当前值但列表框不显示当前值我也是 Listbox1.refresh() 但对列表框没有任何影响
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    相关资源
    最近更新 更多