Home > DeveloperSection > Forums > Removing an item from a list c#
john rob

Total Post:108

Points:756
Posted on    September-28-2013 4:23 AM

 C# C# 
Ratings:


 1 Reply(s)
 977  View(s)
Rate this:

I am having trouble with removing an item from a list in c#. My current code is below:

for (int i = current.Count - 1; i >= 0; i--)
    {
        foreach (ListItem li in sp_list.Items)
        {
            if (li.Text == current[i].uname)
            {
                current.RemoveAt(i);
            }
        }
    }

The aim of the code is to compare the existing items in a list box with newly added items so I know which items have just been added. So currently I am getting the current list box items from the database (they are stored here, it is a databound list box), entering these into a list and for each of the list items, comparing them with the items in a list box and if they match, remove the item from the list.

Therefore, in the end, if I add two new entries, the list should only be storing the two newly added values.

The code does not work as the first item is removed fine, but then, the value of i is greater than current.count - and therefore I get an out of range exception!

Could someone help me with this issue? Apologies about the confusing question, it's hard to explain! Thanks



Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    September-28-2013 6:49 AM

Hey Jhon!

Once you've found the matching value, and removed it from the list, you want to break out of the inner loop to check the next item.

        if (li.Text == current[i].uname)
        {
            current.RemoveAt(i);
            break;
        }

Don't want to miss updates? Please click the below button!

Follow MindStick