got_fr
got_fr

Reputation: 39

how to populate a Dictionary list of class in vb.net

sorry for the title i don't see a better one for my problem.

In VB.NET i have a dictionary(key, list(of )) to add element in the dictionary i create a temporary list and add the list to the dictionary. when i finish to add it i clear the list. But doing that it also clear the value i add to the dict. I can't figure out why

here is my code :

Public Class MesuresVar


Private _Moyenne_Comp As Single



Public Shared DicOfControl As New Dictionary(Of String, List(Of CtrlItem))  
Public Event VariableChanged(ByVal Val As Object, UpdateCtrl As String)


Public Sub New()
    Dim Tmp_List As New List(Of CtrlItem)
    Dim f As New frmAcc
    Tmp_List.Add(New CtrlItem With {.Ctrl = f.L_Moy_G, .prop = "Text"})
    Tmp_List.Add(New CtrlItem With {.Ctrl = f.GaugeSACCG, .prop = "Mesure"})
    DicOfControl.Add("_Moyenne_Comp", Tmp_List)
    Tmp_List.Clear()

End Sub

Public Property Moyenne_Comp As Single
    Get
        Return _Moyenne_Comp
    End Get
    Set(value As Single)
        _Moyenne_Comp = value

        RaiseEvent VariableChanged(_Moyenne_Comp.ToString, "_Moyenne_Comp")
    End Set
End Property
End Class

Thanks

Upvotes: 0

Views: 880

Answers (3)

got_fr
got_fr

Reputation: 39

Ok, thanks all.

i rewrite a little bit my code to mix with what you told me andsomething i found clear...

here it is :

       DicOfControl.Add("_Moyenne_Comp", New List(Of CtrlItem))

    DicOfControl("_Moyenne_Comp").Add((New CtrlItem With {.Ctrl = frmAcc.L_Moy_G, .prop = "Text"}))
    DicOfControl("_Moyenne_Comp").Add((New CtrlItem With {.Ctrl = frmAcc.GaugeSACCG, .prop = "Mesure"}))

So no temporary variable (at least not seeing in the code ;-) )

Upvotes: 0

the_lotus
the_lotus

Reputation: 12748

The list you add is the same as the list you clear. Don't clear it.

Public Sub New()
    Dim Tmp_List As New List(Of CtrlItem)
    Dim f As New frmAcc
    Tmp_List.Add(New CtrlItem With {.Ctrl = f.L_Moy_G, .prop = "Text"})
    Tmp_List.Add(New CtrlItem With {.Ctrl = f.GaugeSACCG, .prop = "Mesure"})
    DicOfControl.Add("_Moyenne_Comp", Tmp_List)
End Sub

This code would also do the same thing, might help you understand what is happening.

Public Sub New()
    Dim Tmp_List As New List(Of CtrlItem)
    Dim f As New frmAcc
    DicOfControl.Add("_Moyenne_Comp", Tmp_List)
    Tmp_List.Add(New CtrlItem With {.Ctrl = f.L_Moy_G, .prop = "Text"})
    Tmp_List.Add(New CtrlItem With {.Ctrl = f.GaugeSACCG, .prop = "Mesure"})
End Sub

Upvotes: 1

Honeyboy Wilson
Honeyboy Wilson

Reputation: 185

When you add Tmp_List to the dictionary, you are not adding a copy of the list.You are adding a reference to the list. The temp list you clear is the same as the temp list in the dictionary.

There is no need to clear the list. Just let the Tmp_List variable go out of scope when the constructor ends.

Upvotes: 1

Related Questions