开发者

Adding property to TreeNode

开发者 https://www.devze.com 2023-01-06 15:53 出处:网络
I have a webpage that uses a Treeview. In the treeview are nodes and i use the Text and Value property, but i need one more. I need one boolean property called IsFile.

I have a webpage that uses a Treeview. In the treeview are nodes and i use the Text and Value property, but i need one more. I need one boolean property called IsFile.

I make the Nodes and add them to the tree programmatically. I have a class Called NavTreeNodes that inherits the TreeNode class and ads this bool.

public class NavTreeNode : TreeNode
{
    private bool _IsFile;

    public bool IsFile
    {
   开发者_运维技巧     get { return _IsFile; }
        set { _IsFile = value; }
    }

    public NavTreeNode()
    { }
}

And when i make a new TreeNode i use this class. Everything works until i try to get the data from the treeview in the SelectedNodeChanged on the TreeView function.

protected void treeview_Navigation_SelectedNodeChanged(object sender, EventArgs e)
{
    TreeNode node = treeview_Navigation.SelectedNode;
    NavTreeNode NNode = node as NavTreeNode;

    Response.Write(NNode.IsFile.ToString());
}

I get a "Object reference not set to an instance of an object." error when i try this. I cant even get the Value or the Text value using this method.


Create new class that holds your value and IsFile property and put it in Value property of node.

        [Serializable]
    public class ValueAndIsFile {
            [XmlAttribute]
            public bool IsFile {get; set;}

            [XmlAttribute]
            public string Value { get; set; }
     }

        ...

        TreeNode nd =  new TreeNode ();
        ValueAndIsFile val = new ValueAndIsFile(){ IsFile = true, Value = yourValueObject};

        nd.Value =SerializeToString(val);
        treeView.Nodes.Add(nd);

        ....

        protected void treeview_Navigation_SelectedNodeChanged(object sender, EventArgs e)
        {
            TreeNode node = treeview_Navigation.SelectedNode;
            ValueAndIsFile val = DeserializeFromString<ValueAndIsFile>(node.Value);            
            Response.Write(val.IsFile.ToString());

    }


     public static string SerializeToString(object obj)
      {
        XmlSerializer serializer = new XmlSerializer(obj.GetType());

       using (StringWriter writer = new StringWriter())
       {
        serializer.Serialize(writer, obj);
        return writer.ToString();
       }
    }

    public static T DeserializeFromString<T>(string  str)
      {
        XmlSerializer serializer = new XmlSerializer(typeof(T) );

         using (StringReader reader =new StringReader(str) )
         {
             return (T)serializer.Deserialize(reader);          
         }
    }

Not sure that solution with serialization is best, but it solves the problem


You can use property Tag and store additional data there.

0

精彩评论

暂无评论...
验证码 换一张
取 消