DataTable.Compute() Method

   If any of you have worked with the .net DataGrid from Visual Studio 2003, then right off the bat I am going to say sorry. I am personally not a huge fan of it and whenever I use it, it results in a lot of frustration and a few muttered choice words. I'm sorry, but I'm so in love with the Infragistics UltraGrid that I haven't had time to really get involved with the MS DataGrid. Anyway, I digress.

   A client of mine had made a request to take the total of a column from the MS DataGrid and in turn, spit it out into a TextBox. Alright... So my first reaction was to loop through each individual record in the grid. It would have worked, but it would not have been pretty, nor speedy by any means. Then I got to wondering if the DataGrid itself had means of calculating the total of a column. I did some quick research on the subject and alas, I could not find a total for the DataGrid. From there I got to thinking, "Well, if the grid is really just an interpretation of it's DataSource, maybe I should be looking at the DataTable?"

Bingo.

   I would like to present to you DataTable.Compute! With this Method, you are able to return a result you are looking for by using simple DataColumn Expressions. In my instance, I wanted to return the sum of one Column. In order to get this result, here's what I had dumped into the TextBox:
textBox1.Text = "$" + dtPurchases.Compute("SUM(Amount)", string.Empty).ToString();
   I was able to successfully return the total Amount from the grid. Classy! From here, you could even expand the functionality of the Compute method and use the second input to filter your results. Say we wanted to return only Billy's results, we could do so by easily searching specifically for their results:

textBox1.Text = "$" + dtPurchases.Compute("SUM(OrigEquityAmt)", "UserName = 'Billy'").ToString();

 

   Excellent! This is quite a time saver compared to older grid totalling methods, such as looping through each row, accumulating the total of a column. I believe it's also a lot more efficient than querying the sum apart from the grid results from a SQL Database. Regardless of how you want to look at it, DataTable.Compute sure saved me a little trouble!

Tags: Technology, .net, Microsoft, DataTable