TreeNode : Cast base class into sub class 
Author Message
 TreeNode : Cast base class into sub class

I have some problems casting a base class into
a sub class.

I have a class TreeNodeNew which is derived from class TreeNode.
I added some new properties to the derived class.

Now Im trying to fill a TreeView by recursion in a Windows Form:

private void AddNode(TreeNodeNew newTreeNode)
{
    nodeCounter += 1;
    if (nodeCounter == 1)
        AddNode(this.treeView1.Nodes.Add(nodeCounter.ToString()));
    if (nodeCounter < 10)
        AddNode(newTreeNode.Nodes.Add(nodeCounter.ToString()));

Quote:
}

Compiling this code, I get casting Errors, because the function "Add" returns
a TreeNode object and not a TreeNodeNew object.

How can I solve this problem ?



Tue, 07 Jun 2005 16:23:51 GMT  
 TreeNode : Cast base class into sub class

Quote:
>How can I solve this problem ?

Create the new TreeNodeNew instance yourself, and then use the
Add(TreeNode) method instead.

private void AddNode(TreeNodeNew newTreeNode)
{
    nodeCounter += 1;
    TreeNodeNew tnn = new TreeNodeNew();
    tnn.Text = nodeCounter.ToString();
    if (nodeCounter == 1)
        this.treeView1.Nodes.Add(tnn);
    if (nodeCounter < 10)
        newTreeNode.Nodes.Add(tnn);
    AddNode(tnn);

Quote:
}

Mattias

===

http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.



Tue, 07 Jun 2005 20:11:41 GMT  
 TreeNode : Cast base class into sub class
Assuming you have a TreeNodeNew constructor that takes a TreeNode as
argument, you could try this -

AddNode (new TreeNodeNew
(this.treeView1.Nodes.Add(nodeCounter.ToString())));

Design suggestion-
I'm not sure what you're trying to accomplish though, cause you will
end up having two disjoint sets of data - the treenode collection and
treenodenew collection. You may want to embed additional data into the
"Tag" property of a tree node instead of subclassing TreeNode.

-S-
No way is the way. No limitation is the limitation.

Quote:

> I have some problems casting a base class into
> a sub class.



Wed, 08 Jun 2005 02:18:49 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. Converting from Base Class to Sub-Class

2. how to convert base class pointer to sub class pointer

3. How do I cast base class to a derived class

4. Protected member in a base class of a base class

5. class class-name: base-class : interface

6. Trying to add a class with no base class in Class Wizard

7. Prevent casting back to a base class

8. Casting derived class to base gives incorrect results w/multiple inheritance

9. Casting derived class to base gives incorrect results w/multiple inheritance

10. VC++ class inheriting C# class loses base functions

11. How to Stop Derived Class from overriding base class method

12. std::vector holding different class types sharing a same base class

 

 
Powered by phpBB® Forum Software