C# SQL SUM value to a label

后端 未结 2 1332
半阙折子戏
半阙折子戏 2020-12-21 07:17

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\

相关标签:
2条回答
  • 2020-12-21 07:28

    DataTable is overkill for single value retrieval, besides your not even accessing the value correctly, better way is to use execute scalar:

    var query = "SELECT SUM (Price) FROM Bill";
    using (var cmd = new OleDbCommand(query, DBcon))
    {
        TotalValueLabel.Text = cmd.ExecuteScalar().ToString();
    }
    
    0 讨论(0)
  • 2020-12-21 07:51

    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 try calling 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);
    }
    
    0 讨论(0)
提交回复
热议问题