Prevent duplicate items from being added to a ListBox

If you bind the lstBoxToUserProjects list box to a datasource (HashSet) then you could do a simple check to see if the item proposed for selection was already in the destination:

foreach(ListItem itemToAdd in itemsToAdd)
{
    if (selectedItems.Contains(itemToAdd)) continue;
    lstBoxToUserProjects.Items.Add(itemToAdd);
}

Note I'm proposing a HashSet because then you can do a performant check on the set whereas a List would have to be enumerated to check for a match.


You should just call ListBox.Items.Contains() in an if statement to check if it has already been added.

foreach (ListItem listItem in itemsToAdd)
{
    if (!lstBoxToUserProjects.Items.Contains(listItem))
    {
        lstBoxToUserProjects.Items.Add(listItem);
    }
}

Try this:

protected void btnAddSelectedItem_Click(object sender, EventArgs e)
{
    lstBoxToUserProjects.Items.AddRange(lstbxFromUserProjects.Items.Where(li => !lstBoxToUserProjects.Items.Contains(li)).ToArray());
}

This assumes C# 3.5, at least.