locked
how to eliminate duplicate entries in dropdownlist RRS feed

  • Question

  • User-43865706 posted

    Hi all,
    am adding the excelsheet names to dropdownlist
    problem is if the existing file is uploaded for overwrite then the dropdownlist values are added twice ,how can i validate that the item with same name must be added only once

    Thanks inadvance

    Saturday, March 24, 2012 10:05 AM

Answers

  • User-691245060 posted

    Using Linq - if you have list, the have List.Distinct() to get unique items...then bind it to DDL...if in case you are adding DDL items for the second time, then do DDL.Item.Clear() to remove all previous entries...

    Thanks,

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 26, 2012 1:15 PM

All replies

  • User-1984520607 posted

    check this:

    var collection = new List<string>
    {"Test","Google","Test"};
    foreach (var elem in collection)
    {
    if(!drpCountry.Items.Contains(new ListItem(elem)))
    {
    drpCountry.Items.Add(new ListItem(elem));
    }
    }

    Saturday, March 24, 2012 10:27 AM
  • User-557958221 posted

    Hi,

    Please try following code

    public static void RemoveDuplicateItems(DropDownList ddl)

     {
         for (int i = 0; i < ddl.Items.Count; i++)

       {

           ddl.SelectedIndex = i;

          string str = ddl.SelectedItem.ToString();

         for (int counter = i + 1; counter < ddl.Items.Count; counter++)

        {

         ddl.SelectedIndex = counter;

       string compareStr = ddl.SelectedItem.ToString();

       if (str == compareStr)

      {

        ddl.Items.RemoveAt(counter);

       counter = counter - 1;

      }

    }

     }

     }

    Monday, March 26, 2012 11:44 AM
  • User-2143928827 posted

    1.Use dropdownlist.items.clear() prior to the upload from list method call.

    2. remove the duplicates if the above suggestion not suites your requirement

     

     

    ----------------------------------------------
    Please "mark as answer" if it helps.

     

    Monday, March 26, 2012 12:49 PM
  • User1088758208 posted
    Hi try it

    var usedNames = {};
    $
    ("select[name='ddlList'] > option").each(function () {
       
    if(usedNames[this.text]) {
            $
    (this).remove();
       
    } else {
            usedNames
    [this.text] = this.value;
       
    }
    });
    Monday, March 26, 2012 12:57 PM
  • User-691245060 posted

    Using Linq - if you have list, the have List.Distinct() to get unique items...then bind it to DDL...if in case you are adding DDL items for the second time, then do DDL.Item.Clear() to remove all previous entries...

    Thanks,

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 26, 2012 1:15 PM