将值从一个列表框交换到另一个列表框时出现异常

时间:2013-04-03 12:21:53

标签: c# winforms listbox datasource

我有两个列表框。当我将值从一个列表框交换到另一个列表框时,我得到异常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;
        }

    }

对于绑定Listbox,我使用此代码

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

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

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

改为改变数据源,这将是_empComponent.GetEmpCodeWithName()

背后的数据结构

答案 1 :(得分:0)

在数据源列表中进行更改 - 在分配之前将其保存在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;

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