It's always fun to customize and draw .NET graphical user control to suite specific needs of our application. In .NET framework 2.0 custom painting of Windows user controls is very easy and even beginners can master the art of custom painting in couple of days.Today we would like to explain you how to change the colors of TreeView nodes using a sample C# program. The sample program which we are going to create now displays selected nodes of a TreeView control in Red color. Start following these simple steps
- Open Visual Studio.NET 2005 editor and create a new C# Windows project
- Open Form1 in designer mode
- Drag and drop a TreeView control on the Form1
- Add few nodes to the TreeView control(use the property Nodes to add nodes)
- Set the property DrawNode of the TreeView control to OwnerDrawText
- Add the following code to DrawNode event of the TreeView control and execute the project. That's all you see selected nodes in red color.
private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
//Paint text of selected node in red color
if ((e.State & TreeNodeStates.Selected) != 0)
//Paint text of other nodes in default color
e.DrawDefault = true;
If you observer the above DrawNode event code, selected nodes are identified with the criteria (e.State & TreeNodeStates.Selected) != 0 . And the selected node's text is painted in red color by specifying Brushes.Red as third parameter in the e.Graphincs.DrawString method. Now its your time to play with this event and customize painting of nodes. Enjoy programming.