Display SubTotal and Grand Total using C# and VB.Net in ASP.Net GridView

Last Reply 5 months ago By pandeyism

Posted 5 months ago

I have tried to to subtotal and grandtotal of qty Catagory wise but that not working here is my complete code

HTML

<asp:GridView ID="GVBigbaldailyrpt" runat="server" AutoGenerateColumns="False" OnDataBound="OnDataBound"
    OnRowCreated="OnRowCreated">
    <Columns>
        <asp:BoundField DataField="Artical" HeaderText="Artical" ItemStyle-Width="60">
            <ItemStyle Width="60px"></ItemStyle>
        </asp:BoundField>
        <asp:BoundField DataField="Catagory" HeaderText="Catagory" ItemStyle-Width="210">
            <ItemStyle Width="210px"></ItemStyle>
        </asp:BoundField>
        <asp:BoundField DataField="QTY" HeaderText="QTY" ItemStyle-Width="60" ItemStyle-HorizontalAlign="Right">
            <ItemStyle HorizontalAlign="Right" Width="60px"></ItemStyle>
        </asp:BoundField>
    </Columns>
</asp:GridView>

C# code

SqlConnection con = new SqlConnection("Data Source=DESKTOP-5PJ76B9;Integrated Security=SSPI;Initial Catalog=SilverProduction;MultipleActiveResultSets=True;");
protected void Page_Load(object sender, EventArgs e)
{
    con.Open();
    {
        SqlCommand cmd = new SqlCommand("Bigbaldailyreport2");
        cmd.Connection = con;
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        GVBigbaldailyrpt.DataSource = dt;
        GVBigbaldailyrpt.DataBind();
        con.Close();
    }
}

int currentid = 0;
decimal subTotal = 0;
decimal total = 0;
int subTotalRowIndex = 0;
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
    subTotal = 0;
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
        String currentid = Convert.ToString(dt.Rows[e.Row.RowIndex]["Catagory"]);
        total += Convert.ToDecimal(dt.Rows[e.Row.RowIndex]["QTY"]);
        if (Catagory != currentid)
        {
            if (e.Row.RowIndex > 0)
            {
                for (int i = subTotalRowIndex; i < e.Row.RowIndex; i++)
                {
                    subTotal += Convert.ToDecimal(GVBigbaldailyrpt.Rows[i].Cells[2].Text);
                }
                this.AddTotalRow("Sub Total", subTotal.ToString("N2"));
                subTotalRowIndex = e.Row.RowIndex;
            }
            currentid = Catagory;
        }
    }

}

private void AddTotalRow(string p1, string p2)
{
    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
    row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
    row.Cells.AddRange(new TableCell[3] { new TableCell (), //Empty Cell
                                    new TableCell { Text = labelText, HorizontalAlign = HorizontalAlign.Right},
                                    new TableCell { Text = value, HorizontalAlign = HorizontalAlign.Right } });

    GVBigbaldailyrpt.Controls[0].Controls.Add(row);
}

protected void OnDataBound(object sender, EventArgs e)
{
    for (int i = subTotalRowIndex; i < GVBigbaldailyrpt.Rows.Count; i++)
    {
        subTotal += Convert.ToDecimal(GVBigbaldailyrpt.Rows[i].Cells[2].Text);
    }
    this.AddTotalRow("Sub Total", subTotal.ToString("N2"));
    this.AddTotalRow("Total", total.ToString("N2"));
}

public string labelText { get; set; }
public string value { get; set; }
public string Catagory { get; set; }            

here is my tables structure with data.

Table (Catagory)

CID Catagory Name
1 Pakistan
2 India

Table (Section)

SecID Section Name
1 HR
2 MIX

Table Item

itemID Item Name  
1 Pant  
2 Shirst  
3 Jeans  

 Tabel  Production

ID itemID SecID CID QTY
1 1 1 1 1
2 1 1 1 1
3 2 2 2 1
4 2 2 2 1
5 3 1 1 1

 I want this out Put(Catagory wise subtotal)

Pakistan

Item Name Section name Catagory Name QTY
Pant HR Pakistan 2
  SubTotal 2

INDIA

Shirt MIX India 2  
Jeans HR India 1  
                                        SubTotal 3

                                   GrandTotal   = 5

 

You are viewing reply posted by: pandeyism 5 months ago.
Posted 5 months ago

Hi akhter,

Refer below sample.

HTML

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnDataBound="OnDataBound"
    OnRowCreated="OnRowCreated">
    <Columns>
        <asp:BoundField DataField="CID" HeaderText="CID" />
        <asp:BoundField DataField="CatagoryName" HeaderText="CatagoryName" />
        <asp:BoundField DataField="QTY" HeaderText="QTY" DataFormatString="{0:N2}"
            ItemStyle-HorizontalAlign="Right" />
    </Columns>
</asp:GridView>

Namespaces

C#

using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;

VB.Net

Imports System.Drawing
Imports System.Data
Imports System.Data.SqlClient

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindGrid();
    }
}

private void BindGrid()
{
    string query = "SELECT c.CID,s.ItemName, i.SectionName ,c.CatagoryName, SUM(QTY) QTY FROM Section s INNER JOIN Item i ON  s.ItemId = i.SecId INNER JOIN Catagory c ON c.CID = s.ItemId INNER JOIN Production p ON p.ItemId = c.CID GROUP BY s.ItemName, i.SectionName ,c.CatagoryName, c.CID";
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}

int currentId = 0;
decimal subTotal = 0;
decimal total = 0;
int subTotalRowIndex = 0;
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
    subTotal = 0;
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
        int orderId = Convert.ToInt32(dt.Rows[e.Row.RowIndex]["CID"]);
        total += Convert.ToDecimal(dt.Rows[e.Row.RowIndex]["QTY"]);
        if (orderId != currentId)
        {
            if (e.Row.RowIndex > 0)
            {
                for (int i = subTotalRowIndex; i < e.Row.RowIndex; i++)
                {
                    subTotal += Convert.ToDecimal(GridView1.Rows[i].Cells[2].Text);
                }
                this.AddTotalRow("Sub Total", subTotal.ToString("N2"));
                subTotalRowIndex = e.Row.RowIndex;
            }
            currentId = orderId;
        }
    }
}
private void AddTotalRow(string labelText, string value)
{
    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
    row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
    row.Cells.AddRange(new TableCell[3] { new TableCell (), //Empty Cell
                                new TableCell { Text = labelText, HorizontalAlign = HorizontalAlign.Right},
                                new TableCell { Text = value, HorizontalAlign = HorizontalAlign.Right } });

    GridView1.Controls[0].Controls.Add(row);
}

protected void OnDataBound(object sender, EventArgs e)
{
    for (int i = subTotalRowIndex; i < GridView1.Rows.Count; i++)
    {
        subTotal += Convert.ToDecimal(GridView1.Rows[i].Cells[2].Text);
    }
    this.AddTotalRow("Sub Total", subTotal.ToString("N2"));
    this.AddTotalRow("Total", total.ToString("N2"));
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Me.BindGrid()
    End If
End Sub

Private Sub BindGrid()
    Dim query As String = "SELECT c.CID,s.ItemName, i.SectionName ,c.CatagoryName, SUM(QTY) QTY FROM Section s INNER JOIN Item i ON  s.ItemId = i.SecId INNER JOIN Catagory c ON c.CID = s.ItemId INNER JOIN Production p ON p.ItemId = c.CID GROUP BY s.ItemName, i.SectionName ,c.CatagoryName, c.CID"
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(conString)
        Using cmd As SqlCommand = New SqlCommand(query)
            Using sda As SqlDataAdapter = New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dt As DataTable = New DataTable()
                    sda.Fill(dt)
                    GridView1.DataSource = dt
                    GridView1.DataBind()
                End Using
            End Using
        End Using
    End Using
End Sub

Private currentId As Integer = 0
Private subTotal As Decimal = 0
Private total As Decimal = 0
Private subTotalRowIndex As Integer = 0

Protected Sub OnRowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    subTotal = 0
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim dt As DataTable = (TryCast(e.Row.DataItem, DataRowView)).DataView.Table
        Dim orderId As Integer = Convert.ToInt32(dt.Rows(e.Row.RowIndex)("CID"))
        total += Convert.ToDecimal(dt.Rows(e.Row.RowIndex)("QTY"))

        If orderId <> currentId Then

            If e.Row.RowIndex > 0 Then

                For i As Integer = subTotalRowIndex To e.Row.RowIndex - 1
                    subTotal += Convert.ToDecimal(GridView1.Rows(i).Cells(2).Text)
                Next

                Me.AddTotalRow("Sub Total", subTotal.ToString("N2"))
                subTotalRowIndex = e.Row.RowIndex
            End If

            currentId = orderId
        End If
    End If
End Sub

Private Sub AddTotalRow(ByVal labelText As String, ByVal value As String)
    Dim row As GridViewRow = New GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal)
    row.BackColor = ColorTranslator.FromHtml("#F9F9F9")
    row.Cells.AddRange(New TableCell(2) {New TableCell(), New TableCell With {
        .Text = labelText,
        .HorizontalAlign = HorizontalAlign.Right
    }, New TableCell With {
        .Text = value,
        .HorizontalAlign = HorizontalAlign.Right
    }})
    GridView1.Controls(0).Controls.Add(row)
End Sub

Protected Sub OnDataBound(ByVal sender As Object, ByVal e As EventArgs)
    For i As Integer = subTotalRowIndex To GridView1.Rows.Count - 1
        subTotal += Convert.ToDecimal(GridView1.Rows(i).Cells(2).Text)
    Next

    Me.AddTotalRow("Sub Total", subTotal.ToString("N2"))
    Me.AddTotalRow("Total", total.ToString("N2"))
End Sub

Screenshot