Removing duplicate items from a listbox
Hi, I can't figure out how to remove duplicate items from a listbox can anyone help?
I guess a loop which cycles though all the items and checks for ones with the same names would work but I'm just not clever enough to figure out how to do this
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.

Scott LysleRank #49 · 31K reputationPosted Mar 22, 2007, 1:14 PM EDT
private
void button1_Click(object sender, EventArgs e){
string strTmp = textBox1.Text;
if (strTmp == string.Empty)
{
MessageBox.Show("I don't do empty strings", "Missing String");
textBox1.Focus();
return;
}
for (int i = 0; i < listBox1.Items.Count; i++)
{
if(listBox1.Items[i].ToString() == strTmp)
{
MessageBox.Show(strTmp + " is already in the listbox.", "Dupe");
textBox1.Focus();
return;
}
}
// won't get here if there is a duplicate or empty string
listBox1.Items.Add(textBox1.Text);
textBox1.Text = string.Empty;
textBox1.Focus();
}