TOP

ASP.NET C#: DataTable Compute

If you want to perform a sum or count on the records in a DataTable, you can, very simply.

You’ll have to have a DataTable with something in it, like results from a database, then you do this:

// my DataTable is full of customer data and is named "dt"
object newCustomerCount = dt.Compute("count(id)","CustomerID > 100");

Parameters are both strings, (expression,filter)

The Compute function will return as an object, so it is a good idea to have your variable be an object too. The problem is that you often need an integer (number) or a text string to put into a label or textbox. Here’s how you get it there:

// this casts to an integer
int var1 = (int) newCustomerCount;
 
//this converts to a string
lblNewCustomerTotal.Text = newCustomerCount.ToString();

As my ASP.NET instructor Dana taught us, everything derives from OBJECT, and everything has a ToString() method. Moo Dana, good form.

  • RSS
  • email
  • Facebook
  • Twitter
  • del.icio.us

Leave a Reply