How to avoid a System.InvalidCastException

1 posts, 0 answers
  1. Ed
    Ed avatar
    124 posts
    Member since:
    Jan 2008

    Posted 05 Jun 2009 Link to this post

    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
Back to Top