How to set colors to half word of a tree view node in C#??

newnode.backcolor=color.red ; ------> this gives colors to all the nodes in the treeview.


But i need to get colored only a first word. Eg: Java Programs ....i need to color the word Java and not Programs

Thank u....... waiting for the replies..........need it urgent............

Dani AI

Generated

— the quickest reliable approach for a WinForms TreeView is owner-draw (as pointed out). Owner-drawing gives full control over text rendering so a single node can show the first word in one color and the rest in another, while leaving the tree lines/icons intact when using OwnerDrawText. (learn.microsoft.com)

Example (WinForms, owner-draw the text only). This keeps icons/expanders, handles selection, and uses TextRenderer for accurate measuring and crisp text:

// wire up once (Form.Load)
treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;
treeView1.DrawNode += TreeView1_DrawNode;

private void TreeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
    var tv = (TreeView)sender;
    var font = e.Node.NodeFont ?? tv.Font;
    var flags = TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding | TextFormatFlags.NoPrefix;

    // background (selected/non-selected)
    if ((e.State & TreeNodeStates.Selected) != 0)
        e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);
    else
        e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds);

    string text = e.Node.Text ?? "";
    int i = text.IndexOf(' ');
    string first = i > 0 ? text.Substring(0, i) : text;
    string rest = i > 0 ? text.Substring(i + 1) : "";

    // measure first word and draw both parts
    var firstSize = TextRenderer.MeasureText(first, font, new Size(int.MaxValue, e.Bounds.Height), flags);
    var firstRect = new Rectangle(e.Bounds.Left, e.Bounds.Top, firstSize.Width, e.Bounds.Height);
    Color firstColor = ((e.State & TreeNodeStates.Selected) != 0) ? SystemColors.HighlightText : Color.Red;
    TextRenderer.DrawText(e.Graphics, first, font, firstRect, firstColor, flags);

    if (!string.IsNullOrEmpty(rest))
    {
        var restRect = new Rectangle(e.Bounds.Left + firstRect.Width + 2, e.Bounds.Top, e.Bounds.Width - firstRect.Width - 2, e.Bounds.Height);
        Color restColor = ((e.State & TreeNodeStates.Selected) != 0) ? SystemColors.HighlightText : tv.ForeColor;
        TextRenderer.DrawText(e.Graphics, rest, font, restRect, restColor, flags);
    }

    // focus rect
    if ((e.State & TreeNodeStates.Focused) != 0)
        ControlPaint.DrawFocusRectangle(e.Graphics, e.Bounds, firstColor, SystemColors.Highlight);
}

TextRenderer.MeasureText/DrawText with TextFormatFlags gives more consistent results than Graphics.DrawString for UI painting; measure with NoPadding/NoPrefix to avoid extra gaps. Avoid constructing/disposing fonts inside DrawNode (reuse NodeFont or TreeView.Font) for performance. To keep the selection visible when the control loses focus, set HideSelection = false. (learn.microsoft.com)

If the app is WPF, use a DataTemplate with a TextBlock that contains two Run elements (each Run can have its own Foreground) — Inlines/Runs are the native way to color parts of text. For web apps, render HTML (span with CSS) or use a tree component that supports HTML/templates (many vendor controls expose an “isHtml/encodeHtml/template” option). (learn.microsoft.com)

Troubleshooting tips: account for node icons/indent when positioning; cache measured widths if many nodes share the same format; test selection/focus behavior on different Windows themes (highlight colors differ). This builds on ’s owner-draw suggestion while preserving icons and handling selection/focus more robustly.

Recommended Answers

All 4 Replies

Hi,
not sure if you can achieve colouring just a part of the whole word of a node. But you can use different colors for different nodes in a treeview by accessing the particular node and applying style of forecolor or backcolor as required.

Thanks for ur reply.....


but i need to highlight a part of a node....Actually in a treeview a list of names will be displayed like

Divya Vasu
Helen James
now i have to highlight the husbands name alone......

like below

Divya Vasu
Helen James

Set DrawMode property of treeview with OwnerDrawText or OwnerDrawAll.

private void Form1_Load(object sender, EventArgs e)
        {
            treeView1.DrawMode = TreeViewDrawMode.OwnerDrawAll;
            treeView1.DrawNode += new DrawTreeNodeEventHandler(treeView1_DrawNode);
            TreeNode root = new TreeNode("Programming");
            treeView1.Nodes.Add(root);

            root.Nodes.Add("Java Programming");
            root.Nodes.Add("C Programming");
        }

        void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
        {
            string[] s = e.Node.Text.Split(' ');
            e.Graphics.DrawString(s[0], new Font("Arial",10f) ,Brushes.Red , e.Bounds.Location);
            if (s.Length > 1)
            {
                Point newst = e.Bounds.Location;
                newst.X = newst.X + (int) e.Graphics.MeasureString(s[0],new Font("Arial",10f)).Width ;
                e.Graphics.DrawString(s[1], new Font("Arial", 10f), Brushes.Green, newst);
            }
        }

Thank u So much...... I got the output Perfectly..................

Once again Thanks a Lot ............................

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.