This project has moved and is read-only. For the latest updates, please go here.

How to define a calculated column

Some times we need to create a new column which is not present in the data source, based on the values of other columns.
There are 2 types of calculated columns in PdfReport:
a) Row numbers columns
Just set the
column.IsRowNumber(true);
And then a new row number column which is not included in the data source, will be available in the final report.

b) To define a custom calculated column, we need to specify its calculation formula by setting the column.CalculatedField method:

                 columns.AddColumn(column =>
                 {
                     column.PropertyName("CF1");
                     column.CalculatedField(
                         list =>
                         {
                             if (list == null) return string.Empty;
                             var name = list.GetSafeStringValueOf<User>(x => x.Name);
                             var lastName = list.GetSafeStringValueOf<User>(x => x.LastName);
                             return name + " - " + lastName;
                         });
                     column.HeaderCell("Full name");
                     column.Width(3);
                     column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                     column.IsVisible(true);
                     column.Order(4);
                 });

column.CalculatedField method's argument gives us the list of the values of current row:
public void CalculatedField(bool isCalculatedField, Func<IList<CellData>, object> calculatedFieldFormula)

Now we have time to build the current cell's value based on the other columns values. There are some helper methods defined in PdfRpt.Core.Helper namespace such as GetSafeStringValueOf to help working with IList<CellData> data more easily.
Defining a PropertyName is mandatory, but in this case it can be an arbitrary text.

Here is the full sample which shows how to define a calculated column:

CalculatedFields

Last edited Nov 5, 2012 at 7:56 AM by VahidN, version 1

Comments

No comments yet.