Distinct values in data bound combobox

11,058

You can do this, (you may have to tweak it a bit to complie and work for you)

ddlName.DataSource = items.Select(item=>item.Name).Distinct().ToList();
ddlName.DataBind();

ddlSize.DataSource = items.Select(item=>item.Size).Distinct().ToList();
ddlSize.DataBind();

ddlPrice.DataSource = items.Select(item=>item.Price).Distinct().ToList();
ddlPrice.DataBind();

And then find the itemID based on the selection of all three dropdown lists.

This is C# and assumes that you have LINQ

Hope this helps.

Edit-- (if no LINQ)

IList<string> names = new List<string>();

foreach (Item item in Items)
    if (!names.Contains(item.Name))
        names.Add(name);

ddlName.DataSource = names;
ddlName.DataBind();

//Do similar for price and size.

Edit (use SQL commands)

select distinct Name from Item
select distinct Size from Item
select distinct Price from Item
Share:
11,058
SMUsamaShah
Author by

SMUsamaShah

Working at Jagex.

Updated on June 04, 2022

Comments

  • SMUsamaShah
    SMUsamaShah almost 2 years

    I have a table Inventory(ItemId,Name,Size,Price,otherinfo) where ItemId is primary key and Name,Size,Price are unique.
    When I bind the combobox with Name all repeated names appear while i want each name to appear just once, same happens with Size.

    How to load unique values in combobox which is bound to a datasource?

  • SMUsamaShah
    SMUsamaShah about 13 years
    What if i don't have LINQ? I am making it in .net 2.0. What is 'items' in this code?
  • SMUsamaShah
    SMUsamaShah about 13 years
    I have a dataset and tableadapters to get values or sql itself