2014-04-07 40 views
1

我正在嘗試搜索活動目錄以從中獲取用戶詳細信息。我用下面的細節填充標籤。它工作正常,但如果說用戶沒有'分區'的價值,那麼它爆炸與下面的錯誤信息。我嘗試過不同的東西,但不能讓它工作在標籤文本幫助中顯示空或「」!搜索活動目錄,並返回null或「」到c#中的標籤,如果屬性爲空

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(); 
    } 

錯誤我得到的是

指數超出範圍。必須是非負數且小於集合的大小。

回答

1

您需要檢查,看是否給定的屬性設置與否:

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

這是AD的工作方式 - 你基本上需要爲任何屬性來完成這個檢查不是必需的財產。任何不可爲空的東西都可以在AD中「未設置」,因此.Properties["...."]將會是null

+0

這太棒了!我說得對,但語法不對。謝謝你爲我節省了很多時間! – wubblyjuggly

相關問題