Gohyu
Gohyu

Reputation: 478

C# - Remove items from List when button is clicked

My problem is; When click a button I input items in List, next in DropDownList. Problem is where i click button again exist items again into my DropDown.

How to solve this problem(sorry for image)?

enter image description here

   List<string> companyList = new List<string>();

   foreach (string item in companyList.ToList())
   {
     companyList.Remove(item); ----> this not working.......
   }

   foreach (SPListItem item in myItemCol)
   {
     companyList.Add(item["Company"].ToString());
   }

   companyList.Sort();

   foreach (string item in companyList.Distinct())
   {
      ddComFilter.Items.Add(item.ToString());
   }

Upvotes: 1

Views: 1711

Answers (3)

Roman
Roman

Reputation: 12171

You should clear your dropdown before adding list as items:

   companyList.Sort();

   ddComFilter.Items.Clear();  // clear
   foreach (string item in companyList.Distinct())
   {
      ddComFilter.Items.Add(item.ToString());
   }

Upvotes: 2

sujith karivelil
sujith karivelil

Reputation: 29026

You could check for existence of the item before add it to the list.

foreach (SPListItem item in myItemCol)
   {
     if(!companyList.Contains(item["Company"].ToString())
     {
       companyList.Add(item["Company"].ToString());
     }
   }

Then you need to clear the ddComFilter before adding the values to it:

companyList.Sort();
ddComFilter.Items.Clear();
foreach (string item in companyList.Distinct())
   {
      ddComFilter.Items.Add(item.ToString());
   }

Alternate solution:

You can bind the ddComFilter using the generated list, instead for iterating the collection and add one-by-one. if so you need not to clear the collection, remove items etc. The code for this will be:

ddComFilter.Datasource = companyList;
ddComFilter.DataBind();

Here is an useful article for you

Upvotes: 3

Alfie Goodacre
Alfie Goodacre

Reputation: 2793

You can use the Contains method to check if it is already there

if(!ddComFilter.Items.Contains(items.ToString())
{
    ddComFilter.Items.Add(item.ToString());
}

This will only add the item if it is not already in the dropdown

Upvotes: 3

Related Questions