Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent duplicate items from being added to a ListBox

I have this code for adding selected items from one ListBox to another. How can I prevent the user from adding an item twice? I want the ListBox they are adding to lstBoxToUserProjects to only contain distinct items with no duplicate entries.

protected void btnAddSelectedItem_Click(object sender, EventArgs e)
{
    List<ListItem> itemsToAdd= new List<ListItem>();

    foreach (ListItem listItem in lstbxFromUserProjects.Items)
    {
        if (listItem.Selected)
            itemsToAdd.Add(listItem);
    }

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

EDIT: Here's what I ended up using

protected void btnAddSelectedItem_Click(object sender, EventArgs e)
{
    List<ListItem> itemsToAdd= new List<ListItem>();

    foreach (ListItem listItem in lstbxFromUserProjects.Items)
    {
        if (listItem.Selected)
            itemsToAdd.Add(listItem);
    }

    foreach (ListItem listItem in itemsToAdd)
    {

        if (!lstBoxToUserProjects.Items.Contains(listItem)) 
        {
            lstBoxToUserProjects.Items.Add(listItem);
        }
    }
}
like image 534
Ronald McDonald Avatar asked Feb 23 '12 19:02

Ronald McDonald


3 Answers

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.

like image 77
kaj Avatar answered Nov 12 '22 09:11

kaj


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);
    }
}
like image 29
cain Avatar answered Nov 12 '22 10:11

cain


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.

like image 2
Krizz Avatar answered Nov 12 '22 11:11

Krizz