Bassicly im creating a program that reads information from an xml file into a lisbox and allows the user to transfer items in the list box to another listBox.
But i want to some how disallow multiple items from being imported from one listBox to the other. I thought i can somehow do an experession to check if the String already Exists in the listBox.
The reason i want to do this is because the user can click x amount of times in order to import items and it’s unproffesional.
Any Help would be appreciated thank you.
private void button1_Click(object sender, EventArgs e)
{
if (!listBox.Items.Exists) // Random Idea which doesnt work
{
listBox2.Items.Add(listBox1.Items[listBox1.SelectedIndex]);
}
}
That will work actually, but you need to use the
Containsmethod. However, you may be missing one crucial point.What type of items are you using to populate your
ListBox?Existswill call.Equalswhich, by default, uses reference equality. So, if you need to filter based on value, you need to override.Equalsfor your type and change the semantics.For example:
However, if we override
.Equalsto provide value type semantics…And now your call to
if(!listBox.Items.Contains(item))will work as you intended it to. However, if you wish it to continue working you will need to add the item to both listboxes, not justlistBox2.