【问题标题】:How to calculate the sum of particular column values in gridview using C# .net如何使用 C# .net 计算 gridview 中特定列值的总和
【发布时间】:2016-03-10 18:18:15
【问题描述】:

我正在将一个学校 ERP 项目作为 ASP.NET Web 应用程序工作,其中我们有一个 gridview。在我的页面上,我想计算 gridview 的列值的总和,但我使用的代码返回特定列总数的两到三倍。关于我们如何计算特定列的正确总数的任何建议?

这里我使用一个复选框列表,其中包含以下项目

Apr-16,May-16,Jun-16,jul-16,Aug-16,Sep-16,Oct-16,Nov-16,Dec-16,Jan-16,Feb-16,Mar-16

当我们从 cheboxlist 中选择 Apr-16 复选框时,gridview 显示 Aprl-16 月费,当我们选择 Apr-16,May-16 时,gridview 显示 Apr-16,May-16 费用详情。

当我们选择 May-16,Jun-16,Jul-16 然后 gridview 显示 May-16,Jun-16,Jul-16 三个费用明细。

我想要这样的输出:

现在我想计算我的 gridview 中特定列的总和

这是我的代码:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Collections.Generic;

namespace egurkul
{
    [Serializable]
    public class field
    {
        public string duemonth { get; set; }
        public decimal Admission_Fee { get; set; }
        public decimal Prospectus_Registration_Fee { get; set; }
        public decimal Maintenance_Fee { get; set; }
        public decimal Computer_Fee { get; set; }
        public decimal Examination_Fee { get; set; }
        public decimal Tution_Fee { get; set; }
    }

    public partial class feeRecipt : System.Web.UI.Page
    {
        SqlCommand cmd;
        SqlConnection con;
        string duemonth;
        int i;

        decimal TotalAdmission_Fee, TotalProspectus_Registration_Fee, TotalMaintenance_Fee, TotalComputer_Fee, TotalExamination_Fee, TotalTution_Fee;
        decimal Admission_Fee, Prospectus_Registration_Fee, Maintenance_Fee, Computer_Fee, Examination_Fee, Tution_Fee;

        DataTable dt;
        List<field> data = null; 
        decimal Total = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                getddlclass();
                bindchbxlstduedate();
            }
        }

        public void getddlclass()
        {
             SqlConnection con = new SqlConnection();
             con.ConnectionString = ConfigurationManager.ConnectionStrings["con1"].ConnectionString;

             con.Open();
             SqlDataAdapter da = new SqlDataAdapter("select *from class", con);
             DataSet ds = new DataSet();
             da.Fill(ds);

             ddlclassname.DataSource = ds;
             ddlclassname.DataTextField = "class_name";
             ddlclassname.DataValueField = "class_id";
             ddlclassname.DataBind();
             ddlclassname.Items.Insert(0, new ListItem("--Select--", "0"));

             con.Close();
        }

        public void bindchbxlstduedate()
        {
            using (SqlConnection conn = new SqlConnection())
            {
                 con = new SqlConnection();
                 con.ConnectionString = ConfigurationManager.ConnectionStrings["con1"].ConnectionString;

                 con.Open();
                 SqlCommand cmd = new SqlCommand();
                 cmd.Connection = con;

                 cmd.CommandText = "Readduedat";
                 cmd.CommandType = CommandType.StoredProcedure;

                 using (SqlDataReader sdr = cmd.ExecuteReader())
                 {
                     while (sdr.Read())
                     {
                         ListItem item = new ListItem();
                         item.Text = sdr["duemonth"].ToString();
                         item.Value = sdr["duedateid"].ToString();
                         chbxlstduedate.Items.Add(item);
                     }
                 }

                 con.Close();
           }
     }

     protected void chbxlstduedate_SelectedIndexChanged(object sender, EventArgs e)
     {
         for (i = 0; i < chbxlstduedate.Items.Count; i++)
         {
            if (chbxlstduedate.Items[i].Selected)
            {
                duemonth = Convert.ToString(chbxlstduedate.Items[i]);
                SqlConnection con = new SqlConnection();
                con.ConnectionString = ConfigurationManager.ConnectionStrings["con1"].ConnectionString;
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "readfeeshead";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@duemonth", duemonth);
                cmd.Parameters.AddWithValue("@classname", Convert.ToString(ddlclassname.SelectedItem));
                cmd.Parameters.AddWithValue("@feecatename", Convert.ToString(ddlstcategory.SelectedItem));
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                       duemonth1 = sdr["duemonth"].ToString();
                       Admission_Fee1 = sdr["Admission_Fee"].ToString();
                       Prospectus_Registration_Fee1 = sdr["Prospectus_Registration_Fee"].ToString();
                       Maintenance_Fee1 = sdr["Maintenance_Fee"].ToString();
                       Computer_Fee1 = sdr["Computer_Fee"].ToString();
                       Examination_Fee1 =sdr["Examination_Fee"].ToString();
                       Tution_Fee1 = sdr["Tution_Fee"].ToString();

                    }
                }

                con.Close();

                if (data == null)
                    data = new List<field>();

                field f1 = new field();

                f1.duemonth = duemonth1;

                if (Admission_Fee1 == "")
                {
                    f1.Admission_Fee = Convert.ToDecimal(0);
                }
                else
                {
                   f1.Admission_Fee = Convert.ToDecimal(Admission_Fee1);
                }

                if (Prospectus_Registration_Fee1 == "")
                    {
                        f1.Prospectus_Registration_Fee = Convert.ToDecimal(0);
                    }
                    else
                    {
                        f1.Prospectus_Registration_Fee = Convert.ToDecimal(Prospectus_Registration_Fee1);
                    }
                    if (Maintenance_Fee1 == "")
                    {
                        f1.Maintenance_Fee = Convert.ToDecimal(0);
                    }
                    else
                    {
                        f1.Maintenance_Fee = Convert.ToDecimal(Maintenance_Fee1);
                    }
                    if (Computer_Fee1 == "")
                    {
                        f1.Computer_Fee = Convert.ToDecimal(0);
                    }
                    else
                    {
                        f1.Computer_Fee = Convert.ToDecimal(Computer_Fee1);
                    }
                    if (Examination_Fee1 == "")
                    {
                        f1.Examination_Fee = Convert.ToDecimal(0);
                    }
                    else
                    {
                        f1.Examination_Fee = Convert.ToDecimal(Examination_Fee1);
                    }
                    if (Tution_Fee1 == "")
                    {
                        f1.Tution_Fee = Convert.ToDecimal(0);
                    }
                    else
                    {
                        f1.Tution_Fee = Convert.ToDecimal(Tution_Fee1);
                    }
                    data.Add(f1);
                    ViewState["_data"] = data;
                    GridView1.DataSource = data;
                    GridView1.DataBind();

            }


        }

    }



 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DataRowView dtview = e.Row.DataItem as DataRowView;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            Label lbladmissionfee = (Label)e.Row.FindControl("lbladmissionfee");
            TotalAdmission_Fee = TotalAdmission_Fee + Convert.ToDecimal(lbladmissionfee.Text);

            Label lblcomputerfee = (Label)e.Row.FindControl("lblcomputerfee");
            TotalComputer_Fee = TotalComputer_Fee + Convert.ToDecimal(lblcomputerfee.Text);

            Label lblExaminationfee = (Label)e.Row.FindControl("lblExaminationfee");
            TotalExamination_Fee = TotalExamination_Fee + Convert.ToDecimal(lblExaminationfee.Text);

            Label lblMaintenancefee = (Label)e.Row.FindControl("lblMaintenancefee");
            TotalMaintenance_Fee = TotalMaintenance_Fee + Convert.ToDecimal(lblMaintenancefee.Text);

            Label lblProsepectusRegistrationFee = (Label)e.Row.FindControl("lblProsepectusRegistrationFee");
            TotalProspectus_Registration_Fee = TotalProspectus_Registration_Fee +Convert.ToDecimal(lblProsepectusRegistrationFee.Text);

            Label lblTutionfee = (Label)e.Row.FindControl("lblTutionfee");
            TotalTution_Fee = TotalTution_Fee + Convert.ToDecimal(lblTutionfee.Text);


        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {

            Label lbl_totaladmissionfee = (Label)e.Row.FindControl("lbl_totaladmissionfee");
            lbl_totaladmissionfee.Text = TotalAdmission_Fee.ToString();

            Label lbl_totalcomputerfee = (Label)e.Row.FindControl("lbl_totalcomputerfee");
            lbl_totalcomputerfee.Text = TotalComputer_Fee.ToString();

            Label lbl_Totalexaminationfee = (Label)e.Row.FindControl("lbl_Totalexaminationfee");
            lbl_Totalexaminationfee.Text = TotalExamination_Fee.ToString();

            Label lbl_totalmaintenancefee = (Label)e.Row.FindControl("lbl_totalmaintenancefee");
            lbl_totalmaintenancefee.Text = TotalMaintenance_Fee.ToString();

            Label lbl_TotalProsepectusRegistrationFee = (Label)e.Row.FindControl("lbl_TotalProsepectusRegistrationFee");
            lbl_TotalProsepectusRegistrationFee.Text = TotalProspectus_Registration_Fee.ToString();

            Label lbl_Totaltutionfee = (Label)e.Row.FindControl("lbl_Totaltutionfee");
            lbl_Totaltutionfee.Text = TotalTution_Fee.ToString();



            decimal alltotal = TotalTution_Fee + TotalProspectus_Registration_Fee + TotalMaintenance_Fee + TotalExamination_Fee + TotalComputer_Fee + TotalAdmission_Fee;
            Label lbl_Totalsamount = (Label)e.Row.FindControl("lbl_Totalsamount");
            lbl_Totalsamount.Text = alltotal.ToString();



        }


    }

【问题讨论】:

  • 方法看起来不错。我认为您可能在代码中有一些复制/粘贴问题。看看你在哪里总结注册费。它正在添加 lblMaintenancefee 而不是 lblProspectusRegistrationFee。另外,我想你会想要电脑费而不是入场费...... TotalComputer_Fee = TotalComputer_Fee + Convert.ToDecimal(lbladmissionfee.Text);
  • 亲爱的勃艮第感谢您的回复,我更新了我的代码但我没有得到我想要的结果我仍然得到与我的第一张图片而不是第二张图片结果相同的结果我想要第二张图片的结果请去通过。
  • 让我解释一下,当我们为 1500 年 4 月至 16 月添加两行值并为 5 月至 16 月的入场费添加两行值时,我更新的代码给出了特定列总和的两倍,那么我想要的结果是1500+0 =1500 但我的代码给出结果 3000 我不明白我的代码哪里有问题请告诉我
  • 我真的不知道你的变量来自哪里。您是否在整个页面生命周期中使用相同的变量来计算费用总额?如果是这样,您在 SelectIndexChanged 事件中设置它们,然后在 RowDataBound 事件中再次添加到它。例如,变量 TotalAdmission_Fee 在您更改索引时被设置。然后你在它上面添加。尝试为网格使用单独的变量。

标签: c# .net sql-server


【解决方案1】:

我确定您同意以下代码我个人在我的 Live Project 中尝试过:

double sum = 0.00;
foreach (DataRow dr in dt.Rows)
{
   sum = sum + Convert.ToDouble(dr.ItemArray[6]);
}
txtGrandTotal.Text = sum.ToString();

【讨论】:

    【解决方案2】:

    嗯,我要上班了

    试试这个代码

    int sum = 0;
    for (int i = 0; i < dvData.Rows.Count; ++i)
    {
        sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
    }
    label.text = sum.ToString();
    

    让我知道这是否适合你

    【讨论】:

    • 感谢 Ahsan Aziz,我将此代码放在 RowDataBound 事件中或其他地方
    • 您可以将此代码放在要计算总和的位置并将结果设置为标签。要观察的次要事项是 Cells[any number] 表示列号。该代码应该可以工作。 @user2342574
    • 我使用的是 Web 应用程序而不是 Windows 应用程序,所以这里不是 dataGridView1,而是 GridView1,当我们使用 GridView1 时,我看到一个错误 Error 3 'System.Web.UI.WebControls.TableCell' does not contain a可以找到“值”的定义并且没有扩展方法“值”接受“System.Web.UI.WebControls.TableCell”类型的第一个参数(您是否缺少 using 指令或程序集引用?) E:\ERP egurkul \egurkul\egurkul\feeRecipt.aspx.cs 226 79 egurkul
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 2020-07-20
    相关资源
    最近更新 更多