将一个值表单列表移动到另一个值从列表中删除下一个值

时间:2013-05-31 10:40:46

标签: c# winforms bindingsource

当我将值交换到另一个列表框时,我有两个列表框,它总是从列表中删除下一个值,当我尝试从列表中交换最后一个值时,它从列表中取出前一个值。我试图找到问题,但我没有得到任何结果。以下是供审核的代码部分。

private void MoveListBoxItems(ListBox lstEmployeelist, ListBox lstSelectedEmployees)
{
    ListBox.SelectedObjectCollection sourceItems = lstEmployeelist.SelectedItems;
    List<Master> newsource = this.masterBindingSource.DataSource as List<Master>;
    List<Master> _selectedSource = this.masterSellectedBindingSource.DataSource as List<Master>;

    try
    {
        if (lstEmployeelist.Items.Count > 0)
        {
            for (int i = 0; i <= sourceItems.Count -1 ; i++)
            {
                Master item = sourceItems[i] as Master;
                this.masterSellectedBindingSource.AddNew();
                Master sitems = masterSellectedBindingSource.Current as Master;
                sitems.Empno = item.Empno;
                sitems.FirstName = item.FirstName;
                newsource.Remove((Master)item);
            }

            if (sourceItems.Count > 0)
                this.masterBindingSource.RemoveCurrent();

            this.masterSellectedBindingSource.EndEdit();
            lstSelectedEmployees.DataSource = masterSellectedBindingSource;
            lstSelectedEmployees.DisplayMember = "FirstName";
            lstSelectedEmployees.ValueMember = "Empno";
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

1 个答案:

答案 0 :(得分:-1)

我认为问题在于你遍历sourceItems的方式。

因为你是使用for循环来做的(大概是因为你不能用foreach来做,因为你不能修改集合),当你从集合中删除说明项目1并将其添加到第二个列表时,项目2向上移动后的所有项目。

因此,项目2成为新项目1,项目3成为项目2等,等等......

要解决这个问题,当你决定移动一个项目时,你还需要将i减少1(i--;),这样当for循环再次循环并且i增加时它将返回到相同的索引。


如果您要移动所有项目而不仅仅是选择项目,那么您不应该使用for循环,请使用while而不是这样:

while (sourceItems.Count > 0)
{
    // code here
}