Distinct values in data bound combobox

最后都变了- 提交于 2020-02-21 04:10:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!