Solved

Sum of column in datagrid

Posted on 2006-06-11
5
644 Views
Last Modified: 2008-03-17
Hi, I want tot find the sum of a colum in a datagrid. Below is the code that I am using but the problemm is that if there is no data in the table, it does not work. I get the error message: Cast from type 'DBNull' to type 'Decimal' is not valid.


TotalSoldPrice = objDS.Tables(0).Compute("SUM(SoldBid)", String.Empty).ToString
txtTotalSoldPrice.Text = FormatCurrency(TotalSoldPrice)

Can you tell me how I can get around this. I want to use this code because it is the simplest one that I have found thus far.
Thank you.

P.S, I am using SQL database, SQL Server 2003 and APS.NET and VB.NET
0
Comment
Question by:Dorneika
5 Comments
 
LVL 5

Accepted Solution

by:
t_itanium earned 63 total points
ID: 16883272
hi
instead of this....
TotalSoldPrice = objDS.Tables(0).Compute("SUM(SoldBid)", String.Empty).ToString
txtTotalSoldPrice.Text = FormatCurrency(TotalSoldPrice)

try to iterate ove all rows in the datagrid...  and check for the values..if it is not null...add them to avariable thenn display this variable....


algorithm:

for (each row in datagrid rows)
if (cell is not null)
variable+=cell.value


display variable

cheers
0
 
LVL 34

Assisted Solution

by:Sancler
Sancler earned 62 total points
ID: 16883562
Or if you want to do it from the datatable itself, you can add an expression column, and compute on that.  On these lines

        Dim dc As New DataColumn
        dc.Expression = "ISNULL(SoldBid,0)"
        dc.DataType = GetType(Decimal)
        dc.ColumnName = "SoldBidWithoutNull"
        objDS.Tables(0).Columns.Add(dc)
        TotalSoldPrice = objDS.Tables(0).Compute("SUM(SoldBidWithoutNull)", String.Empty).ToString

The creation of the new column would only need doing once, not every time you wanted to calculate/re-calculate the TotalSoldPrice.

Roger
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question