首页 > 解决方案 > 如果值在 if 语句之外不存在,如何添加到字典中?

问题描述

如果值在 if 语句之外不存在,如何添加到字典中?

我尝试将变量公开:

Public dictAdd As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)

我试过为它制作一个函数:

Public Sub dictEdit(serviceName As String, serviceValue As Integer)
    dictAdd.Add(serviceName, serviceValue)
End Sub

添加:

'dictAdd.Add(serviceName, serviceValue)
 dictEdit(serviceName, serviceValue)

但无论我做什么,我添加到字典中的任何内容都不存在于范围之外(如 if 语句)。我需要在整个代码中添加和删除值。

编辑:

这是我的代码:

Partial Class openapps_myapp
Inherits System.Web.UI.Page

Public dictAdd As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)

Public Sub dictEdit(serviceName As String, serviceValue As Integer)
    dictAdd.Add(serviceName, serviceValue)
End Sub

'Add CBLAvailable item to CBLModifications
 Protected Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click

    'Some code here that gets serviceName and serviceValue from a checkboxlist

    'Add each selected item from CBLAvailable to dictAdd
    'dictAdd.Add(serviceName, serviceValue)
    dictEdit(serviceName, serviceValue)

End Sub

Protected Sub BtnEdit_Click(sender As Object, e As EventArgs) Handles BtnEdit.Click

    'Some code here that defines replaceString

If dictAdd.ContainsKey(replaceString) Then
                CBLModifications.Items.Remove(CBLModifications.Items(i))
               'right here is my error - dictAdd doesn't have any values - it's empty
            End If

End Sub

'More irrelevant code here

标签: asp.netvb.netdictionary

解决方案


推荐阅读