簡體   English   中英

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

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

我想對gridview中的列和行求和,我嘗試了很多方法,但我做不到。 我正在嘗試了解問題所在。 對不起,如果我的代碼一團糟。 我正在使用ASP.NET C#。 現在,僅在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());

您說得對,您的代碼有點混亂;)

我試圖理解您的意思,因此僅在此情況下,您有一個示例,該示例演示如何對行中的值求和,對列中的值求和或對某些列和行進行求和,以便對所有單元格求和。

這些示例假定您沒有跨過一行或多列的單元格,並且值的總和小於“長”大小,並且每個單元格包含“整數”數字。

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編寫,但為方便起見,將它們簡化為for和foreach循環。

希望它能解決您的問題!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM