问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/4753768/distinct-values-in-data-bound-combobox