Skip to main content
GameDev.net gamedev.net
🔒 Locked

[.net] TreeView issues

Started by Endar Feb 18, 2007 at 8:52 PM 1 replies 700+ views
Original Post
Endar
Endar
I'm having a little bit of trouble with the 'Tag' field of a TreeNode. I have a heirarchy in a TreeView, which contains 2 types of nodes. ToDoGroups and ToDoItems. A have a tree of ToDoGroups (which can contain ToDoGroups and ToDoItems), where each node in the tree corresponds to 1 node in the TreeView. At the moment, when a TreeView node is clicked on, I am trying to load a bunch of data from the ToDo tree node that it is associated with. To connect the two associated nodes, in each TreeNode, I am storing a reference (I am assuming a reference, I just use the assignment operator), to the ToDo node in the Tag field of the TreeView TreeNode. The problem is that I need to load different things depending on which ToDo node type the Tree. How do I go about distinguishing the different types from each other? I've tried this:

if( ToDoList_heirarchy.SelectedNode.Tag.GetType() == ToDoList.ToDoItem ){
        this.ToDoList_Notes_Textbox.Text = ((ToDoList.ToDoItem)ToDoList_heirarchy.SelectedNode.Tag).Text;
}
But the compiler complains that "'ToDoList.ToDoItem' is a 'type', which is not valid in the given context". What next? Should I be associating the TreeView and ToDo nodes in a different way?
[size="2"][size=2]Mort, Duke of Sto Helit: NON TIMETIS MESSOR -- Don't Fear The Reaper
mutex
mutex
You want to use the typeof operator, which returns the Type object of a type:
if( ToDoList_heirarchy.SelectedNode.Tag.GetType() == typeof(ToDoList.ToDoItem) ){        this.ToDoList_Notes_Textbox.Text = ((ToDoList.ToDoItem)ToDoList_heirarchy.SelectedNode.Tag).Text;}
Also consider using is and as:
object obj = "hello";Console.WriteLine(obj is string); // trueConsole.WriteLine(obj is int); // falsestring str = obj as string;Console.WriteLine(str == null ? "(null)" : str); // helloForm form = obj as Form;Console.WriteLine(form == null ? "(null)" : form.Text); // (null)

Niksan2
Niksan2
You could always try deriving from TreeNode as well, avoiding the need to use tag.

	interface IMyTreeLoader	{		void LoadData();	}	public class ToDoItem : System.Windows.Forms.TreeNode, IMyTreeLoader	{		public void LoadData()		{			//loadsomedatahere();			foreach (IMyTreeLoader item in Nodes)			{				item.LoadData();			}		}	}	public class ToDoGroup : System.Windows.Forms.TreeNode, IMyTreeLoader	{		public void LoadData()		{			foreach (IMyTreeLoader item in Nodes)			{				item.LoadData();			}		}	}


and as mutex said, use the 'as' keyword.

IMyTreeLoader nodeLoader = node as IMyTreeLoader;if(nodeLoader!=null){    nodeLoader.LoadData();}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.