开发者

Check if item is in a combobox list

开发者 https://www.devze.com 2023-01-25 03:22 出处:网络
I am dynamically populating a winforms combo box by creating a list from a database. List<string> locationList = new List<string>();

I am dynamically populating a winforms combo box by creating a list from a database.

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

        foreach(Data.DataSet.vwGet_RepListRow row in Data.Manager.TAM.RepListViewTableAdapter.GetData())
           locationList.Add(row.Location_City);

        this.LocationComboBox.DataSource = locationList;

The issue I am having is that there are开发者_如何学JAVA right now a total of 3 locations but 65 employees so what is happening is I am getting cities repeated in the combo box. How can I edit this above to check if the new Location_City is not already present in the locationList? If it is not there, then add it but if it is there, then skip it.

Any help would be great.


if (!locationList.Contains(row.Location_City))
    locationList.Add(row.Location_City);

locationList is of type List, which implements IList. Therefore, you can use the Contains method to check if an item is already present.

http://msdn.microsoft.com/en-us/library/system.collections.ilist.aspx

In addition, you can also use a HashSet instead of a List and use its Distinct() method.

http://msdn.microsoft.com/en-us/library/bb359438.aspx


Change your code to include the following check:

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

        foreach(Data.DataSet.vwGet_RepListRow row in Data.Manager.TAM.RepListViewTableAdapter.GetData())
           string locationCity = row.Location_City;
           if (!locationList.Contains(locationCity))
           {
                locationList.Add(locationCity);
           }

        this.LocationComboBox.DataSource = locationList;

First, you get the string that represents the name of the city you want to add on this iteration of the loop. Then, you check and see if that value is already present in the List. If it is not, then you add it; otherwise, you do nothing.


If you are using .net 3 or higher it is much simpler to use LINQ:

this.LocationComboBox.DataSource = 
    Data.Manager.TAM.RepListViewTableAdapter.GetData().
    Select(r => r.Location_City).Distinct().ToArray();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号