C#SQL SUM值到标签 [英] C# SQL SUM value to a label

查看:161
本文介绍了C#SQL SUM值到标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有其中显示了所有项目一个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的和调用的Ex​​ecuteScalar()。这将返回结果的第一行的第一个值。



也不要尝试调用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆