I found a Microsoft example for how to implement an ASP.NET TreeView
with tags here.
Some important steps that are necessary besides just subclassing TreeNode
and adding a Tag
property are:
You must subclass TreeView
and override the CreateNode
method:
public sealed class TaggedTreeView : TreeView {
protected override TreeNode CreateNode() {
return new TaggedTreeNode(this, false);
}
}
This prevents the TreeView
from overwriting your new nodes with TreeNode
s instead of with your extended type of node.
You will need to have that particular constructor available. (It seems to work using the default constructor, too, but there's a good chance there's a good reason why they used this one.)
public sealed class TaggedTreeNode : TreeNode {
object _Tag;
public object Tag { get { return _Tag; } set { _Tag = value; } }
...
protected internal TaggedTreeNode(TreeView owner, bool isRoot)
: base(owner, isRoot) {
}
In order to use the extended TreeView
you will need a Register
line like the following in your markup to import the type:
<%@ Register TagPrefix="asp" Namespace="MyNamespace" Assembly="MyAssembly" %>
...
<asp:TaggedTreeView ID="taggedTreeView" runat="server" />
You must also override LoadViewState
and SaveViewState
in your inherited TreeNode
class:
public sealed class TaggedTreeNode : TreeNode {
...
protected override void LoadViewState(object state) {
var arrState = (object[])state;
_Tag = arrState[0];
base.LoadViewState(arrState[1]);
}
protected override object SaveViewState() {
var arrState = new object[2];
arrState[1] = base.SaveViewState();
arrState[0] = _Tag;
return arrState;
}
This allows the TreeView
to preserve the value of your Tag
properties between postbacks.
Assuming you are using .net and Windows Forms.
You must set DrawMode property of TreeView to TreeViewDrawMode.OwnerDrawAll. Once you do this, treeview's DrawNode event will fire each time a tree node is being drawn. Handle that event and draw your items manually.
You will get DrawTreeNodeEventArgs as the event arguments. State property of it will tell you which state of the tree item you must draw. e.Bounds will help you for determining bounds and you can use e.Graphics for drawing. You can find more detailed information here:
http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.drawnode.aspx
But prepare to invest multiple hours.
Best Answer
I have an answer to my 1st question - How do I override the treeview or treenode, and add it to a webform? (So I can still use the designer?) Do I have to build them into a .dll and load that way? Or can I add .cs files to my project?
Everyone might know how to do this, but it was news to me. Add the extended classes to the App_Code folder in a namespace:
Then, include a reference to that namespace int the web.config file under:
and then call your control in the .aspx file: