It's surprising to see the negative comments about this issue - indeed, TreeNode lacks a straightforward solution as it doesn't have a CssClass
or style
attribute (which seems like a design flaw in my opinion).
I encountered the same requirement and managed to address it by wrapping the TreeNode's "text" within a span that includes class and/or style attributes. It's worth noting that although you might assume that TreeNode.Text
represents the HTML element's innertext, experimentation reveals that setting node.Text
to HTML content will actually render the supplied HTML (thus modifying innerhtml).
For instance,
TreeNode tn = new TreeNode("<span style='color:red;'>ABC</span>");
will display red text rather than literal text containing "span" and so on. Despite being unexpected, this approach does yield the desired outcome.
I would have anticipated TreeNode to include an Html
attribute for updating innerhtml alongside CssClass
and/or style
attributes, while allowing node.Text
to modify innertext separately. Perhaps Microsoft assigned TreeNode to a less experienced developer :)
This worked for me, and I hope it proves helpful to others as well.