C#SQL SUM值到标签 [英] C# SQL SUM value to a label
问题描述
目前,我有其中显示了所有项目一个DataGridView。我想总结所有的价格在价格列,然后反映了一个标签,TotalValueLabel总。这有什么错我的发言
查询字符串=SELECT SUM(价格)从比尔?;
OleDbDataAdapter的dAdapter =新OleDbDataAdapter的(查询,DBconn);
DataTable中源=新的DataTable();
dAdapter.Fill(源);
TotalValueLabel.Text = source.ToString();
您源是一个DataTable如此source.ToString( )不会给你的结果。尝试source.Rows [0] [0]的ToString();
DataTable对象包含了持有价值为你的查询结果中的每一行的DataRow对象的列表。你的情况,但是您可能不需要这个。如果你正在寻找一个值,你应该使用IDbCommand的和调用的ExecuteScalar()。这将返回结果的第一行的第一个值。
也不要尝试调用Dispose实现IDisposable的对象(如dbadapter,命令,连接)。
查询字符串=SELECT SUM(价格)从比尔
使用(System.Data.IDbCommand命令=新System.Data.OleDb.OleDbCommand(查询,DBconn))
{
对象result = command.ExecuteScalar();
TotalValueLabel.Text = Convert.ToString(结果);;
}
I currently have a DataGridView which displays all the item. I would like to sum all the prices in the price column and then reflect the total in a label, 'TotalValueLabel'. What's wrong with my statement?
string query = "SELECT SUM (Price) FROM Bill";
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, DBconn);
DataTable source = new DataTable();
dAdapter.Fill(source);
TotalValueLabel.Text = source.ToString();
Your source is a DataTable so "source.ToString()" will not give you your result. Try "source.Rows[0][0].ToString();"
DataTable object contains a list of DataRow objects which hold values for each row of your query result. In your case however you might not need this. If you are looking for a single value you should use IDbCommand and call ExecuteScalar(). This will return the first value of the first row of your results.
Also do try and call dispose on objects that implement IDisposable (like dbadapter, command, connection).
string query = "SELECT SUM (Price) FROM Bill";
using (System.Data.IDbCommand command = new System.Data.OleDb.OleDbCommand(query, DBconn))
{
object result = command.ExecuteScalar();
TotalValueLabel.Text = Convert.ToString(result);;
}
这篇关于C#SQL SUM值到标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!