Reputation: 33
I'm trying to debug an issue I didnt create and I'm getting the generic error "The given key was not present in the dictionary." Here is the code:
Dim myInfo As New Dictionary(Of Integer, String)
For i As Integer = 0 To Region.GetRegionCount - 1
myInfo.Add(i, Server.HtmlEncode(ContentItem.Properties("StoreInfoRegion" & i).Value.ToString))
Next
Session(SESSION_INFO) = myInfo
When I step thru it the error occurs on the call to "Add", I guess Im confused because it's adding a key not trying to access one.
Thanks!
Upvotes: 0
Views: 6108
Reputation: 12748
You have a pretty big line of code, split it up into it's pieces and you might find where the problem is exactly.
Instead of
myInfo.Add(i, Server.HtmlEncode(ContentItem.Properties("StoreInfoRegion" & i).Value.ToString))
Have
Dim propertyValue As String
propertyValue = ContentItem.Properties("StoreInfoRegion" & i).Value.ToString
propertyValue = Server.HtmlEncode(propertyValue)
myInfo.Add(i, propertyValue)
With this change, I'm pretty sure that you will see the error on the 2nd line where you fetch the value of Properties. This mean you do not have a value for "StoreInfoRegion" & i
You could do
If ContentItem.Properties.ContainsKey("StoreInfoRegion" & i) Then
Dim propertyValue As String
propertyValue = ContentItem.Properties("StoreInfoRegion" & i).Value.ToString
propertyValue = Server.HtmlEncode(propertyValue)
myInfo.Add(i, propertyValue)
End If
But I think you should first understand why there are no value for that key first.
Upvotes: 3