Andrej Tozon's blog

In the Attic


Adventures in Calculus, pt. 2: A Letter to Santa

In previous adventure, we built a simple calculator with some help of DataTables and data binding. Today, with holidays right behind the corner, we'll write a letter to Santa, using the same tools.

DataTable's expressions can include other columns' values and they are not limited to numeric values - they have much power in text operations too. For this example, we'll build a simple tool to transform raw input data to a nice letter to Santa.

Again, we'll create our base calculation class and call it SantaTemplateCalculator. In it's constructor, we'll create a DataTable like in a previous example, with some extra columns, which will represent the data we're going to input:

table.Columns.Add("Name", typeof(string));
table.Columns.Add("Gender", typeof(string));
table.Columns.Add("Behavior", typeof(string));
table.Columns.Add("List", typeof(string));

We'll also expose this fields as properties:

public string Name
    get { return (string)row["Name"]; }
    set { row["Name"] = value; }


Then we'll build a three-part form:

The left-hand side part contains input fields, which we'll bind to our SantaTemplateCalculator class' properties. The middle part serves as a template and is bound to Expression property of our output column. And the value of this output column is shown as a finished letter in the right-hand side label.

Here's a few lines of code to databind our input fields to the SantaTemplateCalculator class:

name.DataBindings.Add("Text", calculator, "Name", true, DataSourceUpdateMode.OnPropertyChanged);
gender.DataBindings.Add("Text", calculator, "Gender", true, DataSourceUpdateMode.OnPropertyChanged);
behavior.DataBindings.Add("Text", calculator, "Behavior", true, DataSourceUpdateMode.OnPropertyChanged);
list.DataBindings.Add("Text", calculator, "List", true, DataSourceUpdateMode.OnPropertyChanged);

If you take a closer look at the template, you'll see nothing but basic string concatenation and references to some variables - these are the names of DataColumns we added to the DataTable.

DataTable's expressions also support some other functions and operators, like the Iif operator, which returns a value based on some simple expression. In the above example the expressions "short list" or "long list" are generated based on how many letters we enter in the List text box.

Our Santa letter generator is now finished. Again - DataTable's expressions, combined with Data Binding options offer a lot of options for developer to automate some simple number or text processing, without writing a lot of code. Expressions are not to be mistaken for SQL Server's computed column - they offer similar (and more limited) functionality, but they are performed on the client, which is a big plus.

Download the source code

To write your letter to Santa right now (it's not too late, you know), launch this tool through this ClickOnce Page and select "Letter to Santa".