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

时间:2015-05-29 10:24:55

标签: c# asp.net gridview

我想在gridview中创建列和行的总和,我尝试了很多方法而且我不能这样做。我想知道什么是错的。对不起如果我的代码很乱。我正在使用ASP.NET C#。现在只需在response.write中显示sum就足够了,稍后我会把它放在一个列/行上。

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());

1 个答案:

答案 0 :(得分:0)

你是对的你的代码有点乱;)

我试图理解你的意思所以只是对于一个案例,你有一个例子,如何对行中的值求和,对列中的值或者列和行的总和进行求和,以便所有单元格的总和。

这些示例假设您没有单元格通过多个行或列,并且您的值的总和小于“长”大小,并且每个单元格包含“整数”的数字。

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;
}

第一种方法显示控制台上的总和。另一个计算特定GridView的总和。这些计数方法可以使用Linq编写,但为方便起见,将它们留作简单的forach和foreach循环。

希望它能解决你的问题!