0

I am getting the below error while computing the SUM with DataTable.

Invalid usage of aggregate function Sum() and Type: String.

I am using the below code:

lblQuestionnaireTotalTime.Text = CalculateMinutes(
                Convert.ToInt32(
                (
                (DataSet)Session["DsQuestionaire"]).Tables["Questions"]
                .Compute("Sum(EstimatedCompletionTime)", "")));

It always throws an error. I have tried the how-to-calculate-the-sum-of-the-datatable-column-in-asp-net and

how-can-i-get-a-sum-for-the-column-pieces-in-a-datatable and some other links but not able to resolve the issue.

Here is how i m adding column to datatable

dtQuestions.Columns.Add(new DataColumn("EstimatedCompletionTime", typeof(Int32)));
Community
  • 1
  • 1
Ram Singh
  • 6,664
  • 35
  • 100
  • 166
  • Naive question but...what's the type of EstimatedCompletionTime? – Adriano Repetti Oct 01 '13 at 07:46
  • Did you try with Sum(Convert(EstimatedCompletionTime, 'System.Int32'))? – Adriano Repetti Oct 01 '13 at 07:48
  • it says Compute method takes only 1 parameter – Ram Singh Oct 01 '13 at 07:53
  • it says "Syntax error in aggregate argument: Expecting a single column argument with possible 'Child' qualifier." – Ram Singh Oct 01 '13 at 07:59
  • Someone here on SO (sorry can't find it now) suggested to use LINQ for something like that (it works with DataTable too). Give it a chance! – Adriano Repetti Oct 01 '13 at 08:01
  • I have mentioned in the question links i have tried but it is also not working with that – Ram Singh Oct 01 '13 at 08:15
  • Out of interest, what does `((DataSet)Session["DsQuestionaire"]).Tables["Questions"].Columns["EstimatedCompletionTime"].DataType` return? Is it possible the type is being changed somewhere? – dash Oct 01 '13 at 08:46
  • actually session is not destroying on LogOut, actually i am converting a 1.1 website to 4.0 and they just used to redirect to login page when click on Logout. that's is the main problem. – Ram Singh Oct 01 '13 at 09:16

3 Answers3

0

You cannot compute Sum of a Column with type string. You need to make sure your column has type integer.

enter image description here

Sadique
  • 22,572
  • 7
  • 65
  • 91
  • Are you sure `(DataSet)Session["DsQuestionaire"]).Tables["Questions"]` has the exact same column type? Can you get its type and check? – Sadique Oct 01 '13 at 07:57
  • actually session is not destroying on LogOut, actually i am converting a 1.1 website to 4.0 and they just used to redirect to login page when click on Logout. that's is the main problem. – Ram Singh Oct 01 '13 at 09:15
0

try to change the column data type

t.Columns["Price"].DataType=typeof(int);
Tanmay Nehete
  • 2,138
  • 4
  • 31
  • 42
0

Convert the string column.

object sumObject = dtTable.Compute("Sum(Convert(" + col_Name + ", 'System.Int32')","");
Balan
  • 421
  • 6
  • 12