Description:
How to Implement an Unbound Calculated Column II
Answer:
The XtraGrid supports the Unbound Columns feature, which allows you to create a grid column not bound to any field in the grid's data source. Values for this column need to be calculated manually, via a dedicated event or using an expression.
This article shows how you can create an unbound column on the data source level.
We appreciate the help provided kindly by Miha Markic (a DX-Squad member) in this article creation.
__________________________________
ADO.NET supports calculated columns and I will show you a simple solution which applies to DataTables.
Take for example the DataTable fetched from database which consists of following columns:
Adding a calculated column is not difficult. Let’s say that I want show user the total price per row. Obviously I need a column which calculates price*quantity. I will name it total.
The syntax for adding such a column is:
C#maintable.Columns.Add("total", typeof(decimal), "price*quantity");
Visual Basicmaintable.Columns.Add("total", System.Type.GetType("System.Decimal"), "price*quantity");
where the first field is the name of the column, the second is type of columns and the third one (most interesting) is the formula which calculates the column value.
Expressions for calculated columns can be more complicated (check out the topic DataColumn.Expression Property in the .NET Framework help file).
The calculated column can be added at any time – before the DataTable is filled, while it is being filed or after it is filled.
The beauty of this approach is that ADO.NET takes care for (re)calculations and all the hassle of updating the column. Hey, it can be also stored to a database if desired.
The other advantage is that you can use the calculated column with all the other controls that support binding.
And the result is…
I’ve shown you how to add a calculated column in ADO.NET. In this article I just scratched the tip of the iceberg.
See also:
How to Implement an Unbound Calculated Grid Column
How to select rows via an unbound checkbox column