Get Max Number from Datatable using the Compute method
July 9th, 2008This is a nifty little thing I came across recently. I wanted to get the maximum value of a number field from a datatable, and learned about the Datatable’s Compute method. It’s really easy to use. The method takes two arguments – an expression argument, which is the aggregate expression you want to use (Count, Max, Sum, etc), and a filter expression, which functions like a SQL WHERE clause. If you don’t want to filter by anything, you can send Nothing for the second argument (Null in C#).
An example:
Dim expression As String
Dim filter as string
Dim maxNum As Integer
‘get maximum job number from table
expression = “Max(JobNumber)”
filter = “JobDate > 12/31/06 AND JobDate < 1/1/08″
maxNum = CInt(tblJobInfo.Compute(expression, filter))
If you don’t want to filter, it would look like this:
expression = “Max(JobNumber)”
maxNum = CInt(tblJobInfo.Compute(expression, Nothing))
Leave a Reply
You must be logged in to post a comment.