Nanaki
Nanaki

Reputation: 197

WPF Sort comboBox items

Using C# WPF, I want to fill a combobox with ítems retrieved from Active Directory, but they are listed in no particular order. I want to sort it from A to Z.

This is the code that retrieves data and fills the combobox.

    public void GetADInfo()
    {
        string ORG = "";         
        DirectoryEntry entry = new DirectoryEntry("LDAP://*****.com");            
        DirectorySearcher dSearch = new DirectorySearcher(entry);

        switch (cmb_org.SelectedIndex)
        {
            case 0:
                ORG = "AAA";
                break;
            case 1:
                ORG = "BBB";
                break;
            case 2:
                ORG = "CCC";
                break;
            case 3:
                ORG = "DDD";
                break;
            case 4:
                ORG = "EEE";
                break;
        }

        dSearch.Filter = "(l=" + ORG + ")";

        foreach (SearchResult sResultSet in dSearch.FindAll())
        {                
            cmb_name.Items.Add(GetProperty(sResultSet, "sn") + ", " + GetProperty(sResultSet, "givenName"));
        }

    }

    public static string GetProperty(SearchResult searchResult, string PropertyName)
    {
        if (searchResult.Properties.Contains(PropertyName))
        {
            return searchResult.Properties[PropertyName][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }

After this code is executed, all ítems appear in the combobox. How can I order them from A to Z?

Upvotes: 2

Views: 6784

Answers (3)

ChrisF
ChrisF

Reputation: 137148

Ideally you should be binding your combo box to a list rather than adding each item one at a time, but which ever way you do it you need to sort your list.

With your current code change your loop like this:

 foreach (SearchResult sResultSet in dSearch.FindAll().OfType<SearchResult>().SortBy(d => d.Name))

if you use a list and binding:

 BoundList = dSearch.FindAll().OfType<SearchResult>().SortBy(d => d.Name);

Here I'm using Name as a placeholder for what you want to sort by, so change that to whatever the real property is.

Upvotes: 0

Emmanuel DURIN
Emmanuel DURIN

Reputation: 4913

Try to update your line of code using LINQ:

foreach (SearchResult sResultSet in dSearch.FindAll())

with

dSearch.FindAll()
       .OfType<SearchResult>()
       .OrderBy( sr => GetProperty(sr, "sn") + ", " + GetProperty(sr, "givenName") ))

Regards

Upvotes: 1

Jonny
Jonny

Reputation: 1161

One way to do it

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

foreach (SearchResult sResultSet in dSearch.FindAll())
{                
     itemlist.(GetProperty(sResultSet, "sn") + ", " + GetProperty(sResultSet, "givenName"));
}
itemlist.Sort();
foreach (string s in itemlist)
{ 
    cmb_name.Items.Add(s);
}

Upvotes: 0

Related Questions