how I can show the sum of in a datagridview column in asp.net

后端 未结 2 1649
无人及你
无人及你 2021-01-23 10:29

i have a datagridview which are used to display a transaction record. And one of the columns in datagridview is \"amount\"

girdview codeenter code here

相关标签:
2条回答
  • 2021-01-23 11:04

    try this...

     int sum = 0;
     for (int i = 0; i < dataGridView1.Rows.Count; ++i)
     {
         sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
     }
    GridViewRow row = GridView1.FooterRow; 
    ((Label)row.FindControl("lbltotal")).Text=sum.ToString();
    
    0 讨论(0)
  • 2021-01-23 11:11

    use table.Compute function

       private void ComputeBySalesSalesID(DataSet dataSet)
    {
        // Presumes a DataTable named "Orders" that has a column named "Total."
        DataTable table;
        table = dataSet.Tables["Orders"];
    
        // Declare an object variable. 
        object sumObject;
        sumObject = table.Compute("Sum(Total)", "EmpID = 5");
    
        //Find label
         GridViewRow footer = dgOpenBal.FooterRow;
         var lblTotal = (Label)footer.FindControl("lblTotal");
         lblTotal.Text = sumObject.ToString();
    }
    

    Another approach use stored procedure to get calculated amount from Sproc

    private void ComputeBySalesSalesID(DataSet ds)
    {
             if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataRow drSum = ds.Tables[0].Rows[0];
                        GridViewRow footer = dgOpenBal.FooterRow;
                        var lblTotal = (Label)footer.FindControl("lblTotal");
                        lblTotal.Text = drSum["sum"].ToString();
                    }
    }
    
    0 讨论(0)
提交回复
热议问题