I have this code to add selected items from one ListBox
to another. How can I prevent a user from adding an item twice? I want ListBox
be added to lstBoxToUserProjects
to contain only individual items without 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: This is 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); } } }
source share