开发者

Move items between list boxes in C#

I developed a webpage in which I used the following code to move the selected items between two list boxes.

It is very slow.

Is there any optimization for this?

protected void MovetoNext_Click(object sender, EventArgs e)
{
    try
    {
        for (int i = 0; i < lstCategory.Items.Count; i++)
        {
            if (lstCategory.Items[i].Selected)
            {
                lstCategory.Items[i].Selected = false;
                lstSelCategory.Items.Add(lstCategory.Items[i]);
                lstCategory.Items.RemoveAt(i);
                i = i - 1;
            }
        开发者_如何学JAVA}
    }
    catch (Exception ex)
    {
    }
}


Another edit: working with asp.net is weird if you're used to winforms. The latest, actually tested this time, version is below

using System.Collections.Generic;

var selectedIndices = lstCategory.GetSelectedIndices();
var killList = new List<ListItem>();

foreach (var selIndex in selectedIndices)
{
    //add the item to remove to the kill list AND to the other listbox
    killList.Add(lstCategory.Items[selIndex]);
    lstSelCategory.Items.Add(lstCategory.Items[selIndex]);
}

foreach (var killMe in killList)
{
    lstCategory.Items.Remove(killMe);
}

Edit: the code below won't work. I thought the problem was a WinForms problem. A webcontrol listbox doesn't have the properties used in the code below.

It's dangerous to loop over selected items/indices while you are removing items in the collection.

Here's a solution (using LINQ) that copies a list of references to the selected items, and then uses the copy to move the items:

var selItems = lstCategory.SelectedItems.Cast<object>().ToList();
foreach (var selItem in selItems)
{
    lstCategory.Items.Remove(selItem);
    lstSelCategory.Items.Add(selItem);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜