I'm trying to add some items to a dictionary object (database ID and value pair) to let the user confirm their selections before they commit. I have this following code section which add an item to the dictionary. After the add I loop through the Dictionary.Keys and print each key/value to a listbox for the user to see. My dictionary object is a public variable on my form and is set in the Form_Load event.
Dim PickListID As Integer If txtPercentOfStream <> "" Then PickListID = cboCoalTypes If Not CoalsInStreamDic.Exists(PickListID) Then CoalsInStreamDic.Add PickListID, txtPercentOfStream End If Else Exit Sub End If
The weird thing is that whenever I add a new key/value pair the value for the new key becomes the value for all existing keys in addition to the new key.
I run this little block before and after interacting with the dictionary
Dim key As Variant For Each key In CoalsInStreamDic.Keys Debug.Print key & "::" & CoalsInStreamDic.item(key) Next key Debug.Print
i.e. user clicks the button and the <em>first</em> think that happens is this above block to confirm the old keys have their original values, but they don't. They have already been replaced with the "new value". Running the block afterwards confirms this.
Why is this happening?Answer1:
The problem is you're not adding the text of the TextBox, but rather the TextBox instead
If you change your code to the following it should work
If txtPercentOfStream <> "" Then Dim PickListID As Integer, PercentOfStream As Integer PercentOfStream = txtPercentOfStream PickListID = cboCoalTypes If Not CoalsInStreamDic.Exists(PickListID) Then CoalsInStreamDic.Add PickListID, PercentOfStream End If Else Exit Sub End If