This is a migrated thread and some comments may be shown as answers.

How to avoid a System.InvalidCastException

0 Answers 121 Views
TreeView
This is a migrated thread and some comments may be shown as answers.
Ed
Top achievements
Rank 1
Ed asked on 05 Jun 2009, 10:47 AM
I found out about this the hard way, so thought I would share my experience.  Using the RadTreeView version 2009 Q1, I was adding a node to a tree and setting its value on the client-side before committing my changes to the server, like so:

  tree.trackChanges();  
  ...  
  var childNode = new Telerik.Web.UI.RadTreeNode();  
  childNode.set_value(++lastNodeValue);           // lastNodeValue is an *integer* 
  parentNode.get_nodes().add(childNode);  
  ...  
  tree.commitChanges();  
 
 

on the client, and

  foreach (ClientOperation<RadTreeNode> operation in RadTreeView1.ClientChanges)  
  {  
    RadTreeNode node = operation.Item;  
    string nodeID = node.Value;       // DANGER! 
    ...  
  }  

on the server.  The last line, string nodeID = node.Value, was causing the following error to occur:

System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.

After some investigation, I realised that I needed to cast the node ID to a string in the client-side code in order to avoid an error on the server!  This proved to be successful:

  tree.trackChanges();   
  ...   
  var childNode = new Telerik.Web.UI.RadTreeNode();  
  // cast lastNodeValue to a *string* to avoid a server-side error 
  childNode.set_value((++lastNodeValue).toString()); 
  parentNode.get_nodes().add(childNode);   
  ...   
  tree.commitChanges();   
  

Maybe in the next release the client-side set_value() function could automatically cast its argument to a string?  Having said that, I don't remember seeing this error in 2008 Q3, so maybe there's a bug somewhere.

Cheers

Ed Graham

No answers yet. Maybe you can help?

Tags
TreeView
Asked by
Ed
Top achievements
Rank 1
Share this question
or