Click here to Skip to main content
15,915,019 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I have a custom class 'Node' inheriting the System.Web.UI.WebControls.TreeNode class. On the SelectedNodeChanged event of the treeview, I am trying to change the type of Treeview.SelectedNode to the custom type, Node. While performing this type casting I am getting the InvalidCastException.

********************EDIT**********************
The SelectedNodeChanged event HANDLER is defined as follows


protected void tvTreeview_SelectedNodeChanged(object sender, EventArgs e)<br />
{<br />
   TreeNode tn = tvTreeview.SelectedNode;<br />
   Node selectednode = (Node)tn;          //Exception thrown at this line<br />
}<br />

**********************************************

Since 'e' is of type EventArgs, there are no properties defined for it.

Can anybody please help me with this problem?

Its urgent!!
Posted
Updated 11-Jul-11 23:15pm
v5
Comments
Apfelmuuus 11-Jul-11 8:16am    
Please show the code how you want to change the type by typecasting. this would help more then tvTreeview_SelectedNodeChanged event!
maithilym 11-Jul-11 8:22am    
I have updated the ques with appropriate code
#realJSOP 11-Jul-11 8:30am    
DO NOT update the question with your answer. Post a solution instead. I removed your change.
Apfelmuuus 11-Jul-11 8:35am    
It wasnt his answer! It was his problem code you have deleted! Can you undo this?
Sergey Alexandrovich Kryukov 11-Jul-11 22:03pm    
First, what you call an event is not an event. Hope it's a handler. I'm still not sure where is the problem. Could you post a code sample. Simple one, please, not all your code. Include: 1) setting a handler (+= operation), 2) handler; 3) code where you cast.
--SA

No Way! You cant typecast a reference to a TreeNode object to a Node object. You can only typecast a TreeNode reference that refers to a Node object. For Example:

TreeNode tn = new Node();
Node n = (Node) tn;


So make sure that tn refers to a Node object.

Regards.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 11-Jul-11 21:59pm    
Isn't it what OP does, according to the description? I think the problem is incomplete question. We need OP's code sample.
--SA
You probably need to cast the sender to the appropriate type instead.

EDIT ==================

You still have to cast the sender to get the selected node:

C#
Treeview tree = sender as TreeView;
Node node = tree.SelectedNode as Node;
 
Share this answer
 
v2
Comments
maithilym 11-Jul-11 8:13am    
Thanks for your instant reply.
But this option does not work as sender is of the type TreeView. Cannot be cast into Node.
#realJSOP 11-Jul-11 8:31am    
See my updated solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900