Reputation: 73
guys in my program I am trying to look for duplicates within my listbox by checking whats being entreated in the textbox, although I cannot seem to make it work, duplicates just get added to the array/listbox, any suggestions?
private void btnAdd_Click(object sender, EventArgs e)
{
string text = txtInitialise.Text;
bool isDuplicate = false;
foreach (var name in lstHoldValue.Items)
{
if (name.ToString().Equals(text))
{
isDuplicate = true;
break;
}
}
if (isDuplicate)
{
MessageBox.Show("This number already exists!");
}
Upvotes: 1
Views: 77
Reputation: 216293
You add elements to your Items collection is this way:
lstHoldValue.Items.Insert(0, "\t" + numArray[i]);
Notice the \t
at the beginning of the string inserted?.
Now, you should consider this \t
when you check for string equality
string text = "\t" + txtInitialise.Text;
(Or just remove the \t
when you insert)
Upvotes: 2
Reputation: 3889
Just to add to the @mybirthname anwser, you can also use linq instead of foreach, like this: var isDublicate = !lstHoldValue.Items.All(x=>x.ToString() != test)
Upvotes: 0