Вопрос

I am trying to do a conditional SUM on a DataTable column. Below code doesn't give proper results for me.

var d = Convert.ToDouble(myDataTable.Compute("SUM(qty_o)", "itemmaster1_id=4636 AND batch=15789")) // returns 0

myDataTable.Select("itemmaster1_id=4636 AND batch=15789") // return 0 rows

'myDataTable' has a record satisfying the filter condition 'itemmaster1_id=4636 AND batch=15789' and I can see it while debugging in the DataTable Visualizer.

The DataTable is bound to a DataViewGrid which is used for dataentry.

Need help.

[EDIT] I did some further debugging and research on this. Sharing the details. There are 3 rows in the DataTable. When I run myDataTable.Select() I get 3 rows. When I call .Compute to sum column values without filter expression, it gives proper results. But when I try to filter (.Select) the 3rd row, I get 0 rows. If I try to filter the first 2 rows, they work perfectly well. Incidentally, the 3rd row is being entered in the DataGridView. So it could be that the datarow in question (3rd row) is not committed or something. But, I am doing all necessary stuff to persist/commit the data into the datasource/datatable, and this is proved by .Select() call and .Compute("SUM(qty_o)", null) call returning correct results. I am confused.

I also happened to see this open bug - http://connect.microsoft.com/VisualStudio/feedback/details/477331/filter-expression-in-datatable-compute-datatable-select-failed and also this - http://support.microsoft.com/kb/891742/en-us. I am praying this isn't an issue for .NET 4.0.

[EDIT 22/August 2013] Still struggling to get a decent workaround. Please help.

[EDIT 16/July 2014] Encountered this issue again. The below Datatable Compute method gives me wrong answer.

double d = Convert.ToDouble(this.DataSourceAsDataTable.Compute("SUM(amount)", "jobtype=1"));

While the below LINQ query works perfectly giving the correct answer.

double n = this.DataSourceAsDataTable
                .AsEnumerable()
                .Where(r => ((r["jobtype"] != DBNull.Value) ? Convert.ToInt32(r["jobtype"]) : 0) == 1)
                .Sum(r => (r["amount"] != DBNull.Value) ? Convert.ToDouble(r["amount"]) : 0);
Это было полезно?

Решение

The issue got fixed after adding the below line of code just above .Compute.

(this.DataSource as BindingSource).EndEdit();

Apparently the data in the grid cell (jobtype column here) was not committed to the underlying datasource. EndEdit did the trick.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top