Shome
Shome

Reputation: 1

Sum of the rows of a particular column of a table using C# sql

There is a field 'price' in a table 'transfer'. I need sum total of the price column and show it to a label, using Asp.Net C#. I have tried several coding, but failed.Here is the code, it shows error in the 4th line

SQLConnection dbConn = new SQLConnection("server=serverName,database=laptop");
dbConn.Open();
SqlCommand query = new SqlCommand("Select Sum(price) FROM transfer");
query.Connection = dbConn;
int sum = (Int32)query.ExecuteScalar();
lbl2.Text = sum.ToString();

Anyone please suggest me an alternate code, or what to change in the present one to make it run. Thanx.

Upvotes: 0

Views: 2465

Answers (2)

Harry.L
Harry.L

Reputation: 3

 con.Open();
 string syntax = "SELECT Sum(price) FROM transfer";
 cmd = new SqlCommand(syntax, con);
 dr = cmd.ExecuteReader();
 dr.Read();
 lbl2.Text = dr[0].ToString();
 con.Close(); 

Upvotes: 0

SmartDev
SmartDev

Reputation: 2862

If the connection string is OK (this could be one issue) and the query is correct (existing table and column) then I suspect that (since the name of the column is Price) you should cast to to Decimal:

Decimal sum = (Decimal)query.ExecuteScalar();

Works from here.

Upvotes: 1

Related Questions