Mohsen B
Mohsen B

Reputation: 3

how to sum string column in c#

I have a table in my database that all of its columns is string. The fields are name,date,price. I put a label on a page and I want show the sum of column price in the label. I try the below code but i have overflow error.

string reqcom = "select sum(cint(trim(price)) from mytable";                        
OleDbCommand cmd = new OleDbCommand(reqcom, reqcon);
cmd.CommandType = CommandType.Text;
reqcon.Open();
OleDbDataReader dtr = cmd.ExecuteReader();        

if(dtr.Read())
    this.totallbl.Text = dtr["price"].ToString();

Upvotes: 0

Views: 469

Answers (1)

Reza Amini
Reza Amini

Reputation: 476

You can cast the value at first, then get sum of them like code below:

select sum(cast(price as decimal(18,0))) from mytable

After that, use cmd.ExecuteScalar() instead of cmd.ExecuteReader(). ExecuteScalar will return just one value. Use the code below:

decimal totalprice = Convert.ToDecimal(cmd.ExecuteScalar());

Upvotes: 1

Related Questions