views:

340

answers:

1

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;
            }
        }
    }
    catch (Exception ex)
    {
    }
}
+1  A: 

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);
}
cfern
selecteditems is not a members of list box control
Sakthivel
I added some code following what msdn documented about webcontrols. It uses the GetSelectedIndices() method instead of a winform's listbox .SelectedItems property.
cfern
It is shows the error "the non-generic type System.web.ui.Webcontrols.Listitem " cannot be used with type arguments Error msg under List<object>()
Sakthivel
I've edited the code again to use a List<ListItem> instead of a List<object>. I'm sorry about the confusion. I tested the code this time on an ASP.Net sample and it appears to work now.
cfern
Thanks for your help . But still i got error in List<ListItem>() shows that "The type or namespace name 'List' could not be found are you missing assebmley reference ?" . Please let me know what namespace i want to include for this ?
Sakthivel
List<T> is a member of System.Collections.Generic. I'll add it to the code.
cfern