Kevin Chun
Kevin Chun

Reputation: 31

List Box Duplicates

I'm having trouble with list boxes.
If I had a text box and an add button which places the data into the list box.
Accidentally entered the same name twice.
How do i prevent the duplicates in my list box?
Do i enter the code into the button section or under the list box?

Upvotes: 2

Views: 2044

Answers (4)

Ershad
Ershad

Reputation: 1

    foreach (ListItem item in yourListITem.Items)
{
    if (item.Text == yourNewListITemText.SelectedItem.Text)
    {
        empAdd = 0;
    }
}
if(empAdd==0)
{
//Item Exist....
}
else
{
//New Add
 yourListBox.Items.Add(new ListItem(yourlistbox.SelectedItem.ToString(), yourlistbox.SelectedValue.ToString()));
}

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460168

You can simply check if it already exists before you add it, e.g. with Linq:

bool contains = lbName.Items.Cast<ListItem>()
    .Any(li => li.Text.Equals(txtName.Text, StringComparison.OrdinalIgnoreCase));
if(!contains)
{
    lbName.Items.Add(new ListItem(txtName.Text));
}

Assuming that you want to compare case-insensitively.

Edit Since you actually want to add full file-paths to the ListBox but you want to prevent that a second file with the same file-name gets added, you can use the Path class:

string fullFilePath = .... 
string fileName = Path.GetFileName(fullFilePath);
bool contains = lbName.Items.Cast<ListItem>()
    .Any(li => Path.GetFileName(li.Text).Equals(fileName, StringComparison.OrdinalIgnoreCase));
if (!contains)
{
    lbName.Items.Add(new ListItem(fullFilePath));
}

Upvotes: 3

dada686
dada686

Reputation: 433

Add the code in the button, you could even add the code to your textBox's event checking live that the text entered is correct.

Upvotes: 0

stuartd
stuartd

Reputation: 73253

In your button click you can have something like this:

  if (this.listBox.Items.Contains(this.txtCustomerName.Text) == false)
  {
     this.listBox.Items.Add(this.txtCustomerName.Text);
  }

Or, if you're using ListItems:

ListItem item = new ListItem(this.txtCustomerName.Text);

if (listBox.Items.Contains(item) == false)
{
   listBox.Items.Add(item);
}

Upvotes: 1

Related Questions