mtoy
mtoy

Reputation: 195

Dictionary<string, int> does not have value

I have problem with put values into Dictionary.

My Code:

Dictionary<string, Dictionary<string, int>> cnDict = new Dictionary<string, Dictionary<string, int>>();

Dictionary<string, int> cn = new Dictionary<string,int>();

cn.Add("DynamicPanel_1", 0);
cn.Add("DynamicPanel_3", 1);
cn.Add("DynamicPanel_4", 0);
this.cnDict.Add("DynamicPanel_2", cn);

cn.Clear();

cn.Add("DynamicPanel2", 1);
cn.Add("DynamicPanel3", 0);
this.cnDict.Add("DynamicPanel1", cn);
foreach(KeyValuePair<string, int> pos in cnDict["DynamicPanel_2"])
{
    MessageBox.Show("DynamicPanel_2 has values: "+ pos.Key + " ----> " + pos.Value.ToString()); ;
}

foreach (KeyValuePair<string, int> pos in cnDict["DynamicPanel_1"])
{
    MessageBox.Show("DynamicPanel_1 has values: " + pos.Key + " ----> " + pos.Value.ToString()); ;
}

This code display wrong messages:

Should be:

What I do wrong ?

Thanks

Upvotes: 1

Views: 66

Answers (1)

Ulugbek Umirov
Ulugbek Umirov

Reputation: 12807

You add same cn object twice to cnDict dictionary. Create new object: replace cn.Clear(); by cn = new Dictionary<string,int>();

Upvotes: 3

Related Questions