从一个列表框交换值到另一个列表框时发生异常
本文关键字:列表 另一个 异常 交换 一个 | 更新日期: 2023-09-27 18:07:09
我有两个列表框。当我交换值从一个列表框到另一个我得到一个异常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";
如何解决这个问题?
这很容易:当您使用DataSource
时,您无法修改Items
集合,因为项目从数据源自动填充。
更改数据源,这将是_empComponent.GetEmpCodeWithName()
在DataSource列表中进行更改-在分配前将其保存在同一个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;
请注意,这种技术不应该经常用于非常大的列表,因为它是缓慢的操作。但这是满足你需求的最简单的方法。