0

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

我该如何解决这个问题?

4

2 回答 2

2

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

改为更改数据源,这将是背后的数据结构_empComponent.GetEmpCodeWithName()

于 2013-04-03T12:25:02.383 回答
0

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

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

于 2013-04-03T12:26:29.413 回答