如何显示最后一行中列的总和结果

时间:2019-01-21 10:07:52

标签: c# vb.net datagridview

我需要将最后一列的总和打印为最后一行下的total_sum。我已使用连接字符串从sql server获取数据。我将如何添加行以打印该结果。

我使用了DataGridView.Rows.Add(),但没有在其下添加行

private void Result_Click(object sender, EventArgs e
{
SqlConnection con1 = new SqlConnection(conString);
con1.Open();
string q1 = "select * from Customer_Transaction where Cust_No ='C0001'";
string q2 = "select sum(Bill_Amount) as Total from   Customer_Transaction where Cust_No ='C0001'";
  SqlCommand cmd = new SqlCommand(q1, con1);
  SqlCommand cmd1 = new SqlCommand(q2, con1);
  cmd.ExecuteNonQuery();
  cmd1.ExecuteNonQuery();

//ResultDataGrid.Rows.Add("TOTALS", q2);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataAdapter ta = new SqlDataAdapter(cmd1);
da.Fill(dataTable_customer_transaction_result);
ta.Fill(dataTable_customer_transaction_result);
ResultDataGrid.DataSource = dataTable_customer_transaction_result;
con1.Close();
da.Dispose();
ta.Dispose();
}

1 个答案:

答案 0 :(得分:1)

我唯一能解决的方法是在dataTable_customer_transaction_result中获取客户数据,然后将它们求和。这是示例代码:

  SqlConnection con1 = new SqlConnection(conString);
        con1.Open();
        string q1 = "select * from Customer_Transaction where Cust_No ='C0001'";
        SqlCommand cmd = new SqlCommand(q1, con1);
        cmd.ExecuteNonQuery(); ;

        //ResultDataGrid.Rows.Add("TOTALS", q2);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dataTable_customer_transaction_result);

        var totalSum = 0.0M;

        foreach (var row in dataTable_customer_transaction_result.Tables[0].Rows)
        {
            totalSum += Convert.ToDecimal(row["Bill_Amount"]);
        }

您可以在Databind事件上对此使用DataGridView。

另一种方法是使用gridview的RowDataBound事件。请仔细阅读本文https://www.c-sharpcorner.com/UploadFile/77a82c/add-row-total-in-gridview-footer-in-Asp-Net/