I am using the following code to access the list of users in my AD, however on the line where I add the users to my combobox I get a null reference exception.
PrincipalContext AD = new PrincipalContext(ContextType.Domain, "mydomainip");
UserPrincipal u = new UserPrincipal(AD);
PrincipalSearcher search = new PrincipalSearcher(u);
foreach (UserPrincipal result in search.FindAll())
{
if (result.DisplayName != null)
{
comboBox2.Items.Add(result.DisplayName);
}
}
Any idea what I'm doing wrong?
I replaced the combobox with a Console.WriteLine(result.DisplayName)
and it works fine.
Not 100% sure if that's the problem - but PrincipalSearcher
really returns a list of Principal
objects.
So if - for whatever reason - your searcher would return something that's not a UserPrincipal
, then your object result
would be null - not it's .DisplayName
property.
So you should change your checking to:
foreach (UserPrincipal result in search.FindAll())
{
if (result != null && result.DisplayName != null)
{
comboBox2.Items.Add(result.DisplayName);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With