I've managed to get the list now, but if a user does NOT have any value in mobile in AD, then it's not possible to select the user in the listbox, it just selects the first person AFTER a person that has a mobile number in AD.
This is the code:
1 public void GetUsersFromOU(string ou)
2 {
3 ListBox2.ClearSelection();
4 txtSms.Text = "";
5 string path = "LDAP://sys001.sys.no/OU=" + ou + ",DC=sys,dc=no";
6
7
8 using (DirectoryEntry de = new DirectoryEntry(path))
9 {
10 de.AuthenticationType = AuthenticationTypes.Secure;
11 string sFilter = String.Format("(&(objectCategory=Person)(objectClass=user))");
12 //these are the attributes that will show
13 string[] attribs = new string[] { "displayName", "mobile",};
14
15 DirectorySearcher ds = new DirectorySearcher(de, sFilter, attribs);
16 int i = 0;
17 using (SearchResultCollection src = ds.FindAll())
18 {
19 foreach (SearchResult sr in src)
20 {
21 StringBuilder name = new StringBuilder();
22 StringBuilder nr = new StringBuilder();
23
24 foreach (string key in attribs)
25 {
26 if (sr.Properties.Contains(key))
27 {
28 foreach (object o in sr.Properties[key])
29 {
30 if (key.ToString() == "displayName")
31 {
32 name.AppendFormat("{0}", o);
33 }
34 if (key.ToString() == "mobile")
35 {
36 nr.AppendFormat("{0}", o);
37 }
38 }
39 }
40 }
41 ListBox2.Items.Add(name.ToString());
42 ListBox2.Items[i].Value = nr.ToString();
43 ListBox2.Items[i].Text = name.ToString();
44
45 i++;
46 txtSms.Text += name.ToString() + "..." + nr.ToString() + "\r\n";
47 name = null;
48 nr = null;
49 }
50 }
51 }
52 }