nothing nothing - 1 month ago 10
C# Question

C# checking for duplicates

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!");
}
else
{
if (this.index < MAX_ITEMS) // MAX_ITEMS or 10
{
// here about splitting strings as per SA's comment but may need to consider that
int dnum;
if (int.TryParse(txtInitialise.Text, out dnum))
{
numArray[this.index++] = dnum; //index is incremented immediately after it is used
txtInitialise.Text = "";
lstHoldValue.Items.Clear();
for (int i = 0; i <= numArray.Length; i++)
{
if (i < index)
{
lstHoldValue.Items.Insert(0, "\t" + numArray[i]);//show array in a listbox
}
}
}
}
}
}

Answer

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)