Something like this:
Dictionary<int, string> myData = new Dictionary<int, string>();
myData.Add(1, "England");
myData.Add(2, "Canada");
myData.Add(3, "Australia");
myTreeView.Node[0].Tag = myData;
Then I want to get this object, how should I do it ?
Like:
string str = new string();
str = myTreeView.Node[0].Tag[2]; // "str" should be equal to "Canada"
myTreeView.Node[0].Tag[1] = "Spain";
str = myTreeView.Node[0].Tag[1]; // now "str" is equal to "Spain"
Second question – what will return this expression:
Dictionary<int, string> myData = new Dictionary<int, string>();
myData.Add(1, "England");
myData.Add(2, "Canada");
myData.Add(3, "Australia");
string str1 = new string();
str = myData[4]; // there isn't such a key as 4
Exception or null ?
Control.Tagis typed asobjectso you’ll need to cast it to access it as aDictionary<int, string>:And similarly to set a value:
If you try to access a non-existent key, a
KeyNotFoundExceptionwill be thrown. You can check if the dictionary contains a given key usingTryGetValueorContainsKey:TryGetValue does the lookup and sets the given variable to the value (it it exists) in a single call, so is usually preferred.