Len L

Len L

  • NA
  • 25
  • 0

Unable to cast object of type 'System.Windows.Forms.TreeNode'

Feb 23 2008 5:40 PM
Hi all,
using the following MS sample code in How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)

To derive the new class
class myTreeNode : TreeNode
{
public string FilePath;

public myTreeNode(string fp)
{
FilePath = fp;
this.Text = fp.Substring(fp.LastIndexOf("\\"));
}
}
To use the new class
// You should replace the bold text file 
// in the sample below with a text file of your own choosing.
// Note the escape character used (@) when specifying the path.
treeView1.Nodes.Add(new myTreeNode (System.Environment.GetFolderPath _
(System.Environment.SpecialFolder.Personal) _
+ @"\TextFile.txt") );

My code is this,

To derive the new class.
public class dbFieldDefNode : TreeNode
{
  public string name;
  public string type;
  public string length;
  public dbFieldDefNode(string fieldName, string fieldType, string fieldLength)
  {
      this.name = fieldName;
      this.type = fieldType;
      this.length = fieldLength;
      this.Text = fieldName;
  }
Using the new class,
    
private void TreeView_AfterSelect(object sender, TreeViewEventArgs e)
      {
        sqlCon con = new sqlCon();  //make connection to SQL server

       con.fieldNames(tv); //function to retrieve field info and populate extra tree node members
//-------begin function-----------------------------------    
 public void fieldNames(TreeView tv)
      {
      //populate selected tree node (table name) with column names, type and length
      sqlCon con = new sqlCon();
      con.connect();
     
      // SQL statement gets the column name, data type and field length
      string  sql;
      sql = "SELECT table_name=sysobjects.name, ";
      sql += "column_name=syscolumns.name, ";
      sql += "datatype=systypes.name, ";
      sql += "length=syscolumns.length ";
      sql += "FROM sysobjects ";
      sql += "JOIN syscolumns ON sysobjects.id = syscolumns.id ";
      sql += "JOIN systypes ON syscolumns.xtype=systypes.xtype ";
      sql += "WHERE sysobjects.name = '";
      sql += tv.SelectedNode.Text;
      sql += "' AND sysobjects.xtype='U' ";
      sql += "ORDER BY sysobjects.name,syscolumns.colid";
      con.command(sql);
      con.ExecuteReader();
      while (con.read())
          tv.SelectedNode.Nodes.Add(new dbFieldDefNode(con.get("column_name"), con.get("datatype"), con.get("length"))); //node);       
         
      con.terminate();
    }
//-------end function-----------------------------------    

        con.terminate();

     casting  e.Node to dbFieldDefNode as per example causes the error
     dbFieldDefNode node = ( dbFieldDefNode)e.Node;
   
      }
ERROR: Unable to cast object of type 'System.Windows.Forms.TreeNode' to type 'dbFieldDefNode'.


Does anyone have any ideas on this?

Answers (2)