Software Engineer
Restauranteur
Photographer
Cynic

26th January 2012

Post

C# DataTable Calculated Columns

I really like the ability of C# DataSets to be able to add calculated columns on-the-fly. This saves you from having to send duplicate data down from your database, and allows you to bind your controls just like any other data-bound control.

Here’s an example. For our employee data, we track a “deactivated date” when the employee is no longer active. If the employee is active (deactivated date is empty), we want to show “Status: Active”. If the employee is inactive, we want to show “Deactivated: xx/yy/zzzz”.

/*Calculated fields*/
oEmpDT.Columns.Add("StatusLabel", typeof(string), String.Format("IIF(em_inactivated>#{0}#,'Deactivated','Status')",DateTime.MinValue));
oEmpDT.Columns.Add("Status", typeof(string), String.Format("IIF(em_inactivated>#{0}#,em_inactivated,'Active')", DateTime.MinValue));

Later, in the databinding (BindField is just a wrapper for Control.DataBindings):

BindField(this.lblStatus, "Text", oEmpDT, "StatusLabel");
BindField(this.txtStatus, "Text", oEmpDT, "Status");

It couldn’t get much simpler!

Tagged: c sharp.NETDataBindinigcalculated columnsprogrammingsoftware developmentdatadatabasederived columnsDataTable