locked
error: Index was out of range. Must be non-negative and less than the size of the collection. RRS feed

  • Question

  • I have two lines of code, below....

    DirectoryEntry directoryResult = ADResult.GetDirectoryEntry();

     lblsAMAccountName.Text = directoryResult.Properties["sAMAccountName"][0].ToString();

    From that I get the following error....

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

    Can anyone point me in the right direction as to why I am receiving this error?

    Please and thanks...

    David

    Wednesday, November 9, 2011 9:19 PM

Answers

  •  directoryResult.Properties["sAMAccountName"]

    returns an empty collection, so when you get the first item in that collection it fails.

    You should first check that there is at least one item there before trying to access it.

    • Proposed as answer by Bob Wu-MT Friday, November 11, 2011 2:58 AM
    • Marked as answer by Bob Wu-MT Friday, November 25, 2011 2:59 AM
    Wednesday, November 9, 2011 9:24 PM