字典使所有键的值等于最新键/值的加法 [英] Dictionary makes value for all keys equal to most recent key/value addition

查看:62
本文介绍了字典使所有键的值等于最新键/值的加法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些项目添加到字典对象(数据库ID和值对)中,以使用户在提交之前确认选择.我有以下这段代码将代码项添加到字典中.添加后,我遍历Dictionary.Keys并将每个键/值打印到列表框中,以供用户查看.我的字典对象是表单上的一个公共变量,并在Form_Load事件中设置.

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

即用户单击按钮,然后 first 认为发生在上面的代码块中,以确认旧键具有其原始值,但没有.它们已经被新价值"所取代.之后运行该块即可确认这一点.

i.e. user clicks the button and the first 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.

为什么会这样?

推荐答案

问题是您没有添加文本框的文本,而是添加了文本框

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

这篇关于字典使所有键的值等于最新键/值的加法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆