简体   繁体   English

Gridview列/行的总和ASP.NET C#

[英]Sum of Gridview columns/rows ASP.NET C#

I want to make sums of columns and rows in a gridview , I tried so many ways and I can't do it. 我想对gridview中的列和行求和,我尝试了很多方法,但我做不到。 I'm trying to understand what's wrong. 我正在尝试了解问题所在。 I'm sorry If my code is a mess. 对不起,如果我的代码一团糟。 I'm using ASP.NET C#. 我正在使用ASP.NET C#。 For now it is enough to show sum only in a response.write, later i'll put it on a column/row. 现在,仅在response.write中显示总和就足够了,稍后我将其放在列/行中。

protected void Button1_Click(object sender, EventArgs e)
    {

        SqlConnection conn = new SqlConnection("Data Source=*****;Initial Catalog=***;User=***;password=**");

        //query para o select das especialidades todas
        string specstring = "SELECT Speciality.Shortname, SUM(1) as contar " +
                            "FROM DoctorEnterpriseDetails INNER JOIN " +
                            "Speciality ON DoctorEnterpriseDetails.Speciality1 = Speciality.SpecialityId INNER JOIN " +
                            " GroupType ON DoctorEnterpriseDetails.GroupId = GroupType.GroupId " +
                            " WHERE (DoctorEnterpriseDetails.EnterpriseId = 48) " +
                            " GROUP BY Speciality.Shortname ";

        SqlCommand command = new SqlCommand(specstring, conn);
        command.Connection.Open();

        SqlDataAdapter myDataAdapter = new SqlDataAdapter();
        myDataAdapter.SelectCommand = command;

        DataTable specstringtable = new DataTable();

        myDataAdapter.Fill(specstringtable);
        specstring = ""; 

        for (int i = 0; i < specstringtable.Rows.Count; i++)
        {

            if (specstring == "")
            {

                specstring = "[" + specstringtable.Rows[i][0] + "]".ToString();
            }
            else
            {
                specstring = specstring + ", " + "[" + specstringtable.Rows[i][0] + "]";

            }

        }


        command.Connection.Close();

        ////query para a pivot table
        string querystring = "SELECT Description AS Categoria, " + specstring +
                             "FROM (SELECT GroupType.Description, Speciality.Shortname, SUM(1) AS contar, GroupType.GroupId " +
                             "FROM DoctorEnterpriseDetails INNER JOIN " +
                             "Speciality ON DoctorEnterpriseDetails.Speciality1 = Speciality.SpecialityId INNER JOIN " +
                             "GroupType ON DoctorEnterpriseDetails.GroupId = GroupType.GroupId " +
                             "WHERE (DoctorEnterpriseDetails.EnterpriseId = 48) " +
                             "GROUP BY GroupType.Description, Speciality.Shortname, DoctorEnterpriseDetails.GroupId, GroupType.GroupId) as ps " +
                             "PIVOT (SUM(contar) FOR Shortname IN (" + specstring + ")) pvt " +
                             "ORDER BY GroupId; ";

        ////Response.Write(querystring);
        SqlCommand command2 = new SqlCommand(querystring, conn);
        command2.Connection.Open();

        SqlDataAdapter myDataAdapter2 = new SqlDataAdapter();
        myDataAdapter2.SelectCommand = command2;


        DataTable cobtable = new DataTable();

        myDataAdapter2.Fill(cobtable);


        DataColumn cl = cobtable.Columns.Add("Total");
        cobtable.Columns["Total"].SetOrdinal(1);

        DataRow dr;
        dr = cobtable.NewRow();
        dr["Categoria"] = "Total";
        cobtable.Rows.InsertAt(dr, 0);
        dr = cobtable.NewRow();
        dr["Categoria"] = "";
        cobtable.Rows.InsertAt(dr, 1);
        dr = cobtable.NewRow();
        dr["Categoria"] = "%";
        cobtable.Rows.InsertAt(dr, 3);
        dr = cobtable.NewRow();
        dr["Categoria"] = "";
        cobtable.Rows.InsertAt(dr, 4);
        dr = cobtable.NewRow();
        dr["Categoria"] = "%";
        cobtable.Rows.InsertAt(dr, 6);
        dr = cobtable.NewRow();
        dr["Categoria"] = "";
        cobtable.Rows.InsertAt(dr, 7);
        dr = cobtable.NewRow();
        dr["Categoria"] = "%";
        cobtable.Rows.InsertAt(dr, 9);

        GroupGrid.DataSource = cobtable;
        GroupGrid.DataBind();

       //GroupGrid.FooterRow.Cells[1].Text = cobtable.Compute("sum(" + cobtable.Columns[3].ColumnName + ")", null).ToString();

        decimal a = 0, soma = 0;
        string la = "";
        //Response.Write(GroupGrid.Rows[0].Cells.Count);

        for (int i = 3; i <= (GroupGrid.Rows[0].Cells.Count); i++)
        {
            Response.Write("!");
            //string l3 = GroupGrid.Rows[6].Cells[i-1].Text;
            // Response.Write(l3);
            Response.Write(GroupGrid.Rows[5].Cells[i - 1].Text);
            // la = GroupGrid.Rows[5].Cells[i - 1].Text;
            // sum += Convert.ToInt32(la);
            //sum =  Convert.ToInt32(GroupGrid.Rows[5].Cells[i - 1].Text.ToString());
            //a = a + sum;
            //GroupGrid.FooterRow.Cells[1].Text = sum.ToString();
        }

       // Response.Write(a.ToString());

You are right your code is a little mess ;) 您说得对,您的代码有点混乱;)

I tried to understand what you mean so just for a case here you have the example how to sum the values in row, sum the values in column or some both columns and rows so sum of all cells. 我试图理解您的意思,因此仅在此情况下,您有一个示例,该示例演示如何对行中的值求和,对列中的值求和或对某些列和行进行求和,以便对所有单元格求和。

These examples assume you are not having cells spaning through more then one row or column and that the total sum of your values is less then "long" size and each cell contains number that is "integer". 这些示例假定您没有跨过一行或多列的单元格,并且值的总和小于“长”大小,并且每个单元格包含“整数”数字。

public void DisplayGridViewSums(GridView gv)
{
    foreach (GridViewRow row in gv.Rows)
    {
        long sum = SumValuesInRow(row);
        Console.WriteLine("Sum of values in raw '{0}' is: {1}", row.RowIndex, sum);
    }

    for (int i=0; i<gv.Columns.Count;i++)
    {
        long sum = SumValuesInColumn(gv,i);
        Console.WriteLine("Sum of values in column '{0}' with header '{1}' is: {2}",i, gv.Columns[i].HeaderText, sum);
    }
    long totalsum = SumColumnsAndRowsInGridView(gv);
    Console.WriteLine("Sum of all cells in each row is: {0}", totalsum);
}

public long SumColumnsAndRowsInGridView(GridView gv)
{
    long sum = 0;
    foreach (GridViewRow row in gv.Rows)
    {
        sum += SumValuesInRow(row);
    }
    return sum;
}

public long SumValuesInRow(GridViewRow row)
{
    long sum = 0;
    foreach (TableCell cell in row.Cells)
    {
        sum += int.Parse(cell.Text);
    }
    return sum;
}

public long SumValuesInColumn(GridView gv, int columnIndx)
{
    long sum = 0;
    foreach (GridViewRow row in gv.Rows)
    {
        sum += int.Parse(row.Cells[columnIndx].Text);
    }
    return sum;
}

First method shows the sums on console. 第一种方法在控制台上显示总和。 The other count the sums for particular GridView. 另一个计算特定GridView的总和。 Those counting methods could be written using Linq but for your convenience a left them as simple for and foreach loops. 这些计数方法可以使用Linq编写,但为方便起见,将它们简化为for和foreach循环。

Hope it solves your problem! 希望它能解决您的问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM