Answered by:
Listview Handeling null returned values

Question
-
Hi,
I am querying Active Directory for Values, and returning them for a listview,
but if the Value does not exists it throws {"Object reference not set to an instance of an object."} System.NullReferenceException
which I want but in the list view I want a Null or blank value and it just aborts the query completely.
foreach (SearchResult searchResult in searchResultCollection) { //Add items in the listview string[] arr = new string[4]; ListViewItem itm; /Add first item arr[0] = searchResult.GetDirectoryEntry().Properties["samaccountname"].Value.ToString(); arr[1] = searchResult.GetDirectoryEntry().Properties["givenname"].Value.ToString(); arr[2] = searchResult.GetDirectoryEntry().Properties["sn"].Value.ToString(); arr[3] = searchResult.GetDirectoryEntry().Properties["displayname"].Value.ToString();
itm = new ListViewItem(arr); userListview.Items.Add(itm); }
it just gives me an error on the display name since some accounts don't contain a display name
any assistance will do?
- Edited by Killer47x Monday, August 14, 2017 7:47 PM
Monday, August 14, 2017 7:46 PM
Answers
-
Try the ‘?.’ operator:
var p = searchResult.GetDirectoryEntry().Properties;
arr[0] = p["samaccountname"]?.Value?.ToString();
. . .If null results should be converted to empty strings, then:
arr[0] = p["samaccountname"]?.Value?.ToString() ?? string.Empty;
- Marked as answer by Killer47x Tuesday, August 15, 2017 8:22 PM
Tuesday, August 15, 2017 5:12 AM
All replies
-
I think this will work
arr[0] = searchResult.GetDirectoryEntry().Properties["samaccountname"].Value.ToString() ?? string.Empty
- Proposed as answer by Wendy ZangMicrosoft contingent staff Tuesday, August 15, 2017 2:47 AM
Monday, August 14, 2017 9:30 PM -
Try the ‘?.’ operator:
var p = searchResult.GetDirectoryEntry().Properties;
arr[0] = p["samaccountname"]?.Value?.ToString();
. . .If null results should be converted to empty strings, then:
arr[0] = p["samaccountname"]?.Value?.ToString() ?? string.Empty;
- Marked as answer by Killer47x Tuesday, August 15, 2017 8:22 PM
Tuesday, August 15, 2017 5:12 AM -
Awesome,
that simple
Thanks You Very Much!!!
Tuesday, August 15, 2017 8:22 PM