wubblyjuggly
wubblyjuggly

Reputation: 969

Search Active directory and return null or "" into a label in c# if property is blank

I am trying to search active directory to get users details from it. I populate labels with their details as below. It works fine BUT if say the user doesn't have a value for 'division' then it bombs out with below error message. I have tried different things but cant get it to work to show null or "" in the label text HELP!

   private void populate_table(string current_user)
    {
        string connection = ConfigurationManager.ConnectionStrings["ADConnection"].ToString();

        DirectorySearcher dssearch = new DirectorySearcher(connection);
        dssearch.Filter = "(sAMAccountName=" + current_user + ")";
        SearchResult sresult = dssearch.FindOne();
        DirectoryEntry dsresult = sresult.GetDirectoryEntry();

        lblfname.Text = dsresult.Properties["givenName"][0].ToString();
        lbllname.Text = dsresult.Properties["sn"][0].ToString();
        lblemail.Text = dsresult.Properties["mail"][0].ToString();
        lblDepartment.Text = dsresult.Properties["department"][0].ToString();
        lblsam.Text = dsresult.Properties["samAccountName"][0].ToString();
        lblBranch.Text = dsresult.Properties["division"][0].ToString();
    }

Error I get is

Index was out of range. Must be non-negative and less than the size of the collection.

Upvotes: 2

Views: 1630

Answers (1)

marc_s
marc_s

Reputation: 754408

You need to check to see if a given property is set or not:

if (dsresult.Properties["division"] != null &&
    dsresult.Properties["division"].Count > 0)
{ 
    lblBranch.Text = dsresult.Properties["division"][0].ToString();
}
else     
{ 
    lblBranch.Text = string.Empty;
}

This is the way AD works - you basically need to do this checking for any property that is not a required property. Anything non-nullable could be "not set" in AD and thus the .Properties["...."] will be null

Upvotes: 2

Related Questions