Calculate GridView Running Sub Total and Grand Total using C# in Asp.net
This Article explain the how to calculate Sub Total And Grand Total in GridView in C# in Asp.net program
Make new Project to Calculate GridView Running Sub Total and Grand Total using C# in Asp.net
Open New Project In Visual Studio and Add New WebForm
# S.total and G.total with Grid view
#Coding
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
namespace WebApplication10
{
public partial class WebForm5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Grid_Bind();
}
private void Grid_Bind()
{
string qry = "select case when(grouping (dname)=1) then 'G.Total' else dname end
dname, case when (grouping (ename)=1) then 'S.Total' else ename end ename,sum
(esal)esal from tbemployee,tbdep where edno=dno group by dname,ename with
rollup";
SqlDataAdapter adp = new SqlDataAdapter(qry,
ConfigurationManager.ConnectionStrings["psg"].ConnectionString);
DataSet ds = new DataSet();
adp.Fill(ds);
string nd,
pd = "";
Int32 i = 0;
while (i<ds.Tables[0].Rows.Count-1)
{
nd =
ds.Tables[0].Rows[i][0].ToString();
if (pd!=nd)
{
pd = nd;
DataRow r =
ds.Tables[0].NewRow();
r[1] = nd;
r[2] = -1;
ds.Tables[0].Rows.InsertAt(r, i);
i++;
}
i++;
}
ds.Tables[0].Rows[ds.Tables[0].Rows.Count - 1][1] = "G.Total";
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells[1].Text=="S.Total")
{
e.Row.BackColor = Color.Aqua;
}
if (e.Row.Cells[0].Text == "G.Total")
{
e.Row.BackColor = Color.Blue;
}
if (e.Row.Cells[2].Text == "-1")
{
e.Row.BackColor =
Color.Coral;
}
}
}
}
|
*ds.Tables[0].Rows[ds.Tables[0].Rows.Count
- 1][1] = "G.Total";- To replace S.Total to G.Total
*end – to end the case
*Else- if row is not made
* Tables[0]- for query
*Rows[i]- number of rows
*Rows[i][0]-[0] columns for
department
* while (i<ds.Tables[0].Rows.Count-1)-
(-1) is used to run the loop one less time
BoundField> header text>
Name>datafield>ename
BoundField> header
text> Salary>datafield>esal
protected void GridView1_RowDataBound(object
sender, GridViewRowEventArgs e)
{
if (e.Row.Cells[0].Text=="S.Total")
{
e.Row.BackColor = Color.Aqua;
}
/* if (e.Row.Cells[0].Text ==
"G.Total")
{
e.Row.BackColor = Color.Blue;
}*/
if (e.Row.Cells[1].Text == "-1")
{
e.Row.BackColor =
Color.Coral;
e.Row.Cells[0].ColumnSpan =
2;
e.Row.Cells[0].Font.Italic = true;
e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Center;
e.Row.Cells.RemoveAt(1);
}
}
|