Search code examples
asp.netvb.netlistboxactive-directorylistboxitems

Populate List box with LDAP cn and name from a specific group


I'm having some trouble figuring this out and this is what I'm trying to do. I'm trying to populate a list box with the "name" as the text displayed and the "cn" as the value from a specific group in Active Directory. My code is below and it's not throwing any errors it's just not populating the list box with anything. My guess is I'm not adding each result properly but I'm stumped.

Dim search As DirectorySearcher = New DirectorySearcher(entry)
            search.PropertiesToLoad.Add("cn")
            search.PropertiesToLoad.Add("name")
            search.PropertiesToLoad.Add("memberOf")
            search.Filter = "(memberOf=SAO Computer Grp)"
            Dim result As SearchResultCollection = search.FindAll()
            Dim ct As Integer = result.Count                
            For i = 0 To ct
                lstEmail.DataTextField = result.PropertiesLoaded("name")
                lstEmail.DataValueField = result.PropertiesLoaded("cn")
                lstEmail.DataSource = result.Item(i)
                lstEmail.DataBind()
            Next

Solution

  • Try the following:

    Dim search As DirectorySearcher = New DirectorySearcher(entry)
    
    search.PropertiesToLoad.Add("cn")
    search.PropertiesToLoad.Add("name")
    search.PropertiesToLoad.Add("memberOf")
    
    search.Filter = "(memberOf=SAO Computer Grp))"
    
    Dim result As SearchResultCollection = search.FindAll()
    Dim de As DirectoryEntry
    Dim firstName, lastName As String
    
    For Each ADUsers As SearchResult In result
        de = ADUsers.GetDirectoryEntry()
        firstName = "NA"
        lastName = "NA"
    
        If de.Properties("name") IsNot Nothing 
           AndAlso de.Properties("name").Count > 0 Then
                firstName = de.Properties("name")(0).ToString()
        End If
    
        If de.Properties("cn") IsNot Nothing 
           AndAlso de.Properties("cn").Count > 0 Then
               lastName = de.Properties("cn")(0).ToString()
        End If
    
        lstEmail.Items.Add(New ListItem(firstName, lastName))
    Next