Sunday, October 21, 2007

C#.NET : Display TreeView Nodes in Different Colors

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

  1. Open Visual Studio.NET 2005 editor and create a new C# Windows project
  2. Open Form1 in designer mode
  3. Drag and drop a TreeView control on the Form1
  4. Add few nodes to the TreeView control(use the property Nodes to add nodes)
  5. Set the property DrawNode of the TreeView control to OwnerDrawText
  6. 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)

   {

       e.Graphics.DrawString(e.Node.Text,

               e.Node.TreeView.Font,

               Brushes.Red,

               e.Bounds);

 

   }

   //Paint text of other nodes in default color

   else

   {

      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.

2 Comments:

selvin said...

Nice coding.. how can i do it Visual C# 2003. because DrawNode event is not available in Visual C# 2003

Anonymous said...

The availability of events does not depend on the version of VS, but solely on the .NET Framework, of which you might have an old version. It might also be possible, however, that VS is simply not showing the event in the designer (this is the case with MouseWheel for Control in VS 2008, for instance). In that case, just open [Form name].Designer.cs and manually add:

this.treeView1.DrawNode += new System.Windows.Forms.DrawTreeNodeEventHandler(treeView1_DrawNode);
somewhere after
this.treeView1 = new System.Windows.Forms.TreeView();
to the method InitializeComponents().