Event Handling

There are different methods for reacting on events in C#.

The most common ones are demonstrated via s simple use case. In the following samples a timer is created and when the tick event occurs a message box shall be displayed.

The approaches to handle events can be transferred to any other event in dotNET.

The usual way by registering a function:

Timer myTimer = new Timer();
myTimer.Tick += new EventHandler(myTimer_Tick);

and later:

void myTimer_Tick(object sender, EventArgs e)

Using an anonymous function:

Timer myTimer = new Timer();
myTimer.Tick += delegate (object sender, EventArgs e)

Using an anonymous function without parameters:

Timer myTimer = new Timer();
myTimer.Tick += delegate

Using Lambda Expressions:

myTimer.Tick += (sender, e) => {

Note that in all examples the event is registered by ‘+=’, which ensures that existing registrations are not removed.

Customize the Tab Appearance of a WinForms TabControl

This article describes by a short example how to customize the tabs in a WinForms TabControl.
In order to customize the look and feel of a TabControl, the DrawItem event must be handled. Be sure to set the DrawMode of your TabControl to OwnerDrawFixed, otherwise your custom event handler will not be called.

#region tabControl1_DrawItem()
private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
	//this eventhandler is called only if:
	//DrawMode = OwnerDrawFixed

	//define how to handle which tabs
	var redTabIdxList = new List<int>() { 0, 1, 2, 3 };
	var orangeTabIdxList = new List<int>() { 4,5,6 };

	//customize the tabs
	if (redTabIdxList.Contains(e.Index))
		var bshBack = new LinearGradientBrush(
		e.Graphics.FillRectangle(bshBack, e.Bounds);
	if (orangeTabIdxList.Contains(e.Index))
		var bshBack = new LinearGradientBrush(
		e.Graphics.FillRectangle(bshBack, e.Bounds);

	//also draw the text
	var fntTab = e.Font;
	var bshFore = new SolidBrush(Color.Black);
	string tabName = this.tabControl1.TabPages[e.Index].Text;
	var sftTab = new StringFormat();
	var recTab = new Rectangle(e.Bounds.X, e.Bounds.Y + 4, e.Bounds.Width, e.Bounds.Height - 4);
	e.Graphics.DrawString(tabName, fntTab, bshFore, recTab, sftTab);

.NET WinForms Chart Control

With framework version 4.0 new WinForms controls were introduced. In this article I am going to play around with the ‘Chart’ control. By default it is located in the toolbox in category data.

Create a new WinForms project and simply drag the control onto the surface.

After playing around with the properties (ChartAreas, Legends, PaletteCustomColors and Series) the user interface looks like this:

dotNet WinForms Chart control

dotNet WinForms Chart control

#region UpdateChart()
private void UpdateChart()
		//update statistics
		double totalRepeatCount = 0;
		double totalRightCount = 0;
		foreach (DataRow statRow in this.QueryStatistics.Rows)
			//obtain values
			var rightCount = Int32.Parse(statRow["RightCount"].ToString());
			var repeatCount = Int32.Parse(statRow["RepeatCount"].ToString());
			var queryID = Int32.Parse(statRow["QueryID"].ToString());

			//display values
			this.chart1.Series[0].Points.AddXY(queryID, rightCount);
			this.chart1.Series[1].Points.AddXY(queryID, repeatCount-rightCount);

			//update values for summary
			totalRepeatCount += repeatCount;
			totalRightCount += rightCount;

		if(totalRepeatCount > 0)
			this.chart1.Titles[0].Text = "Statistics: " + ((totalRightCount / totalRepeatCount) * 100).ToString("0.00") + "%";
	catch (Exception ex)
		MessageBox.Show("Error creating statistics graph: " + ex.Message);

The control´s properties remind a little bit of the Excel Chart wizard properties. After getting used to handling the control, it is a quite neat way to represent data managed in code.

Further Reading

Code Generation and T4 Text Templates

Code generation can save a developer a lot of time. Therefore it becomes more and more important to automate recurring tasks.

Microsoft offers a convenient way to generate code (and any other text based artifacts) with its T4 Text Template engine which is fully integrated in up to date versions of Visual Studio.

In order to play around with it, I was writing a little test application with the following sample code.

1. Project Creation

Launch Visual Studio and create a new Project (I used C# WinForms, but it can be any other Project type).

Add a reference to Microsoft.VisualStudio.TextTemplating (I had to install Visual Studio SDK in order to have it present on my machine).

Right click your project node and choose Add/New Item. Then choose PreprocessedTextTemplate, give it a name (I called it: MyPreTextTemplate.tt)

To the PreProcessedTextTemplate file add the following (sample) content:

<#@ template language="C#" #>
<#@ parameter name="TestParam" type="System.String" #>
<h1>Some Header</h2>
Parameter: <#= TestParam #>
    <# for (int i = 1; i <= 10; i++)
       { #>
         <tr><td>Test name <#= i #> </td>
             <td>Test value <#= i * i #> </td> </tr>
    <# } #>

2. Transforming Text via C#

The following code executes the text transformation of the above template providing a custom parameter called ‘TestParam’:

private string ExecuteProcessedTemplate()
	//create template
	var template = new MyPreTextTemplate();

	//create session
	var session = new TextTemplatingSession();
	session["TestParam"] = "paramValue";
	template.Session = session;

	//execute transformation
	string textTemplateOutput = template.TransformText();
	return processedTextTemplateOutput;

This is the most simple way of transforming text of a text template including parameters. In order to do more sophisticated text generation, check out the ITextTemplatingEngineHost interface (which you need to implement, but there can be found a full working demo implementation in the MSDN).

private string ExecutePreProcessedTextTemplateUsingACustomEngineHost()
	string templateFile = this.Host.ResolvePath("MyPreTextTemplate.tt");
	string templateContent = File.ReadAllText(templateFile);

	CallContext.LogicalSetData("TestParam", "paramValue");

	Engine engine = new Engine();
	string generatedContent = engine.ProcessTemplate(templateContent, this.Host);


	return generatedContent

Further Reading and References

Code Generation and T4 Text Templates


Visual Studio SDK
Reference: Microsoft.VisualStudio.TextTemplating
(C:\Program Files\Microsoft Visual Studio 2008 SDK\VisualStudioIntegration\Common\Assemblies\Microsoft.VisualStudio.TextTemplating.dll)
Installation FAQ

ITextTemplating Interface

Invoking Text Transformation in a VS Extension

Creating Custom Text Template Hosts

Useful .NET Development Tools

In this section there will be a collection of all the ‘must have’ or at least ‘should know’ freeware development tools for dotNET.

dotPeek is a new free .NET decompiler from JetBrains.


#develop (SharpDevelop)
… a free IDE for C#, VB.NET and Boo projects on Microsoft’s .NET platform. It is open-source, and you can download both sourcecode and executables

PowerCommands for Visual Studio 2010

Productivity Power Tools

A tool for simulating and testing WebService requests and responses.

This list may grow as time goes by…
If you know further tools worth being mentioned, please leave a comment.