locked
Need Group Total RRS feed

  • Question

  • User2033107836 posted

    Hello

    I used this below code it works fine

     <asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" 
                 OnRowCreated="GridView3_RowCreated"
                 EnableModelValidation="True">
                <Columns>
                    <asp:BoundField DataField="BelongsTo" Visible="false" HeaderText="BelongsTo" SortExpression="BelongsTo" />
                    <asp:BoundField DataField="ItemName" HeaderText="ItemName" SortExpression="ItemName" />
                    <asp:BoundField DataField="Qty" HeaderText="Qty" SortExpression="Qty" />
                </Columns>
            </asp:GridView>

     public string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    DataTable dt = new DataTable();
                    using (SqlConnection con = new SqlConnection(constr))
                    {
                        string cmdtext = "select BelongsTo, ItemName, Qty from TestTable ";
                        using (SqlCommand cmd = new SqlCommand(cmdtext, con))
                        {
                            con.Open();
                            //cmd.Parameters.AddWithValue("@name", "AAA"); where UserId='@name' and UserPass = @pass"
                            //cmd.Parameters.AddWithValue("@pass", "123123");
                            //cmd.Parameters.AddWithValue("@city", "City");
                            SqlDataAdapter sda = new SqlDataAdapter(cmd);
                            sda.Fill(dt);
                            DataView dv = new DataView(dt);
                            dv.Sort = "BelongsTo ASC";
                            GridView3.DataSource = dt;
                            GridView3.DataBind();
                        }
                    }
                }
            }
            protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
                    string currentNum = string.Empty;
                    string NextNum = string.Empty;
                    if (e.Row.RowIndex >= 1)
                    {
                         currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                         NextNum = dt.Rows[e.Row.RowIndex -1]["BelongsTo"].ToString();
                        if (currentNum != NextNum)
                            AddTotalRow("Belongs To: "+currentNum);
                    }
                    else
                    {
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        AddTotalRow("Belongs To: " + currentNum);
                    }
                }
            }
            private void AddTotalRow( string value)
            {
                GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                row.Cells.Add(new TableCell() { ColumnSpan = 3, Text = value });
                GridView3.Controls[0].Controls.Add(row);
            }

    Output coming like this

    I need Qty Total Like This Below

    Need The Code To Get Qty Total

    Wednesday, April 26, 2017 8:54 AM

Answers

  • User-1509636757 posted

    You should have a running total in RowCreated event.

            protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow && null != e.Row.DataItem)
                {
                    DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
                    if (Session["__dt"] == null)
                        Session["__dt"] = dt;
                    string currentNum = string.Empty;
                    string NextNum = string.Empty;
                    if (e.Row.RowIndex >= 1)
                    {
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        NextNum = dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString();
                        decimal RateTotal = 0;
                        if (currentNum != NextNum)
                            AddTotalRow("Belongs To: " + currentNum, GetTotal(dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString(), out RateTotal).ToString(), RateTotal.ToString());
                    }
                    else if (e.Row.RowIndex == 0)
                    {
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        AddTotalRow("Belongs To: " + currentNum, null, null);
                    }
                }
                else if (e.Row.RowType == DataControlRowType.Footer)
                {
                    if (Session["__dt"] != null)
                    {
                        decimal RateTotal = 0;
                        DataTable dt = (Session["__dt"] as DataTable);
                        AddTotalRow(null, GetTotal(dt.Rows[dt.Rows.Count - 1]["BelongsTo"].ToString(), out RateTotal).ToString(), RateTotal.ToString());
    
                        decimal qtyTotal = 0;
                        decimal rateTotal = 0;
                        foreach (DataRow item in dt.Rows)
                        {
                            qtyTotal += Convert.ToDecimal(item["Qty"]);
                            rateTotal += Convert.ToDecimal(item["Rate"]);
                        }
                        GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                        row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                        row.Cells.AddRange(new TableCell[]
                        { new TableCell() { Text = "Grand Total: ", ForeColor = Color.Red}, new TableCell() { Text = qtyTotal.ToString(), ForeColor = Color.Red}, new TableCell() { Text = rateTotal.ToString(), ForeColor = Color.Red} });
                        GridView3.Controls[0].Controls.Add(row);
                    }
                }
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 8, 2017 12:32 PM

All replies

  • User-1509636757 posted

    Please try:

    public partial class WebForm138 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = GetSampleData();
                GridView3.DataSource = dt;
                GridView3.DataBind();
            }
        }
    
        private DataTable GetSampleData()
        {
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection(constr))
            {
                string cmdtext = "select BelongsTo, ItemName, Qty,(select sum(Qty) from TestTable t1 where t2.BelongsTo = t1.BelongsTo) as total from TestTable t2";
                using (SqlCommand cmd = new SqlCommand(cmdtext, con))
                {
                    con.Open();
                    //cmd.Parameters.AddWithValue("@name", "AAA"); where UserId='@name' and UserPass = @pass"
                    //cmd.Parameters.AddWithValue("@pass", "123123");
                    //cmd.Parameters.AddWithValue("@city", "City");
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    sda.Fill(dt);
                    DataView dv = new DataView(dt);
                    dv.Sort = "BelongsTo ASC";
                    GridView3.DataSource = dt;
                    GridView3.DataBind();
                }
            }
            return dt;
        }
    
        protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
                if (Session["__dt"] != null)
                    Session["__dt"] = dt;
                string currentNum = string.Empty;
                string NextNum = string.Empty;
                if (e.Row.RowIndex >= 1)
                {
                    currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                    NextNum = dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString();
                    if (currentNum != NextNum)
                        AddTotalRow("Belongs To: " + currentNum, "Total:    " + dt.Rows[e.Row.RowIndex]["Total"].ToString());
                }
                else if (e.Row.RowIndex != 0)
                {
                    currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                    AddTotalRow("Belongs To: " + currentNum, "Total:    " + dt.Rows[e.Row.RowIndex]["Total"].ToString());
                }
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                if (Session["__dt"] != null)
                {
                    DataTable dt = (Session["__dt"] as DataTable);
                    AddTotalRow(null, "Total:    " + dt.Rows[dt.Rows.Count - 1]["Total"].ToString());
                }
            }
        }
    
        private void AddTotalRow(string value, string Total)
        {
            GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
            row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
            row.Cells.Add(new TableCell() { ColumnSpan = 3, Text = Total });
            GridView3.Controls[0].Controls.Add(row);
    
            if (!string.IsNullOrEmpty(value))
            {
                row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                row.Cells.Add(new TableCell() { ColumnSpan = 3, Text = value });
                GridView3.Controls[0].Controls.Add(row);
            }
        }
    }

    I also wanted to state that using inline queries in code is the worst code practice and it should be moved to procedure.

    Wednesday, April 26, 2017 10:19 AM
  • User2033107836 posted

    can it be possible to do without (select sum(Qty).......

    Coz my sql query is very big and so can it be possible to do direct

    Wednesday, April 26, 2017 10:27 AM
  • User2033107836 posted

    can it be possible to do without (select sum(Qty).......

    Coz my sql query is very big and so can it be possible to do direct..

    Waiting for your code

    Thursday, April 27, 2017 6:40 AM
  • User-1509636757 posted

    can it be possible to do without (select sum(Qty).......

    Coz my sql query is very big and so can it be possible to do direct..

    Alternatively, you can put the DataTable in Session and write loop to get the SUM for matching BelongsTo field value. However, this may slow down page rendering.

    Thursday, April 27, 2017 7:26 AM
  • User2033107836 posted

    okay 

    Is any way to do it in Row Databound / Row Creaated to get 

    BelongsTo Total of each

    Thursday, April 27, 2017 7:31 AM
  • User-1509636757 posted

    Row Databound / Row Creaated to get 

    Yes, I believe that the loop that I am talking about to get total you will require to write in RowCreated event with the code that you have right now.

    Thursday, April 27, 2017 7:33 AM
  • User2033107836 posted

    Will you please give me the complete code based on my code..

    Thanks lot in advance

    Thursday, April 27, 2017 7:38 AM
  • User-1509636757 posted

    This is not the exact code, but only gives you highlight to what you require to accomplish to get total. You will require to modify it based on your requirement:

    public partial class WebForm138 : System.Web.UI.Page
    {
        private string constr;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = GetSampleData();
                GridView3.DataSource = dt;
                GridView3.DataBind();
            }
        }
    
        private DataTable GetSampleData()
        {
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection(constr))
            {
                string cmdtext = "select BelongsTo, ItemName, Qty from TestTable t2";
                using (SqlCommand cmd = new SqlCommand(cmdtext, con))
                {
                    con.Open();
                    //cmd.Parameters.AddWithValue("@name", "AAA"); where UserId='@name' and UserPass = @pass"
                    //cmd.Parameters.AddWithValue("@pass", "123123");
                    //cmd.Parameters.AddWithValue("@city", "City");
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    sda.Fill(dt);
                    DataView dv = new DataView(dt);
                    dv.Sort = "BelongsTo ASC";
                    GridView3.DataSource = dt;
                    GridView3.DataBind();
                }
            }
            return dt;
        }
    
        protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
                if (Session["__dt"] != null)
                    Session["__dt"] = dt;
                string currentNum = string.Empty;
                string NextNum = string.Empty;
                if (e.Row.RowIndex >= 1)
                {
                    currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                    NextNum = dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString();
                    if (currentNum != NextNum)
                    {
                        AddTotalRow("Belongs To: " + currentNum, "Total:    " + GetTotal(dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString()));
                    }
                }
                else if (e.Row.RowIndex != 0)
                {
                    currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                    AddTotalRow("Belongs To: " + currentNum, "Total:    " + GetTotal(dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString()));
                }
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                if (Session["__dt"] != null)
                {
                    DataTable dt = (Session["__dt"] as DataTable);
                    AddTotalRow(null, "Total:    " + GetTotal(dt.Rows[dt.Rows.Count - 1]["BelongsTo"].ToString()));
                }
            }
        }
    
        private decimal GetTotal(string BelongsTo)
        {
            decimal retResult = 0;
            if (Session["__dt"] != null)
            {
                DataTable dt = (Session["__dt"] as DataTable);
                foreach (DataRow row in dt.Rows)
                {
                    if (Convert.ToString(row["BelongsTo"]).Equals(BelongsTo))
                        retResult += Convert.ToDecimal(row["Qty"]);
                }
            }
            return retResult;
        }
    
        private void AddTotalRow(string value, string Total)
        {
            GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
            row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
            row.Cells.Add(new TableCell() { ColumnSpan = 3, Text = Total });
            GridView3.Controls[0].Controls.Add(row);
    
            if (!string.IsNullOrEmpty(value))
            {
                row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                row.Cells.Add(new TableCell() { ColumnSpan = 3, Text = value });
                GridView3.Controls[0].Controls.Add(row);
            }
        }
    }

    Thursday, April 27, 2017 7:40 AM
  • User2033107836 posted

    it showing two times record

    Please check your side and send me screenshot of output

    Thursday, April 27, 2017 7:52 AM
  • User-1509636757 posted

    it showing two times record

    I suggest you debug and see if there is any data related issue and post your issue. As I said, you will require to modify the code that I posted, based on your code requirement because I do not have any database to connect with that table schema. Please try to at-least debug to try to be your own, otherwise you will be dependent every time for code.

    Thursday, April 27, 2017 8:06 AM
  • User2033107836 posted

    I tried your given code but it changed all the row

    Thats y i asked you to please do share the output screenshot it will be easy for me to understand

    Sorry for asking the code.

    Hope you will do this needful with full code and output screenshot

    Thursday, April 27, 2017 8:12 AM
  • User-1509636757 posted

    As I said, I cannot execute the code since I do not have table/database, You can post your code and screenshot along with the issue to let others/me see what is the problem.

    Thursday, April 27, 2017 8:16 AM
  • User2033107836 posted
    Hope will get code from you after sometime
    Thursday, April 27, 2017 1:27 PM
  • User-1509636757 posted
    public partial class WebForm138 : System.Web.UI.Page
    {
        private string constr = "data source=.;initial catalog=NORTHWND;integrated security=SSPI";
    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = GetSampleData();
                GridView3.DataSource = dt;
                GridView3.DataBind();
            }
        }
    
        private DataTable GetSampleData()
        {
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection(constr))
            {
                string cmdtext = "select BelongsTo, ItemName, Qty from TestTable t2";
                using (SqlCommand cmd = new SqlCommand(cmdtext, con))
                {
                    con.Open();
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    sda.Fill(dt);
                    DataView dv = new DataView(dt);
                    dv.Sort = "BelongsTo ASC";
                    GridView3.DataSource = dt;
                    GridView3.DataBind();
                }
            }
            return dt;
        }
    
        protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
                if (Session["__dt"] == null)
                    Session["__dt"] = dt;
                string currentNum = string.Empty;
                string NextNum = string.Empty;
                if (e.Row.RowIndex >= 1)
                {
                    currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                    NextNum = dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString();
                    if (currentNum != NextNum)
                    {
                        AddTotalRow("Belongs To: " + currentNum, "Total:    " + GetTotal(dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString()));
                    }
                }
                else if (e.Row.RowIndex == 0)
                {
                    currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                    AddTotalRow("Belongs To: " + currentNum, null);
                }
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                if (Session["__dt"] != null)
                {
                    DataTable dt = (Session["__dt"] as DataTable);
                    AddTotalRow(null, "Total:    " + GetTotal(dt.Rows[dt.Rows.Count - 1]["BelongsTo"].ToString()));
                }
            }
        }
    
        private decimal GetTotal(string BelongsTo)
        {
            decimal retResult = 0;
            if (Session["__dt"] != null)
            {
                DataTable dt = (Session["__dt"] as DataTable);
                foreach (DataRow row in dt.Rows)
                {
                    if (Convert.ToString(row["BelongsTo"]).Equals(BelongsTo))
                        retResult += Convert.ToDecimal(row["Qty"]);
                }
            }
            return retResult;
        }
    
        private void AddTotalRow(string value, string Total)
        {
            if (!string.IsNullOrEmpty(Total))
            {
                GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                row.Cells.Add(new TableCell() { ColumnSpan = 3, Text = Total });
                GridView3.Controls[0].Controls.Add(row);
            }
            if (!string.IsNullOrEmpty(value))
            {
                GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                row.Cells.Add(new TableCell() { ColumnSpan = 3, Text = value });
                GridView3.Controls[0].Controls.Add(row);
            }
        }
    }

    Friday, April 28, 2017 9:16 AM
  • User2033107836 posted

    Thanks Kaushal

    Really Thanks Lot For Your Solution

    Can you show total in Qty column that will look alignment perfect. 

    Friday, April 28, 2017 2:34 PM
  • User2033107836 posted

    See Belongs To : A

    Total is showing Wrong

    Friday, April 28, 2017 2:45 PM
  • User-1509636757 posted
        public partial class WebForm138 : System.Web.UI.Page
        {
            private string constr = "data source=.;initial catalog=NORTHWND;integrated security=SSPI";
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    DataTable dt = GetSampleData();
                    GridView3.DataSource = dt;
                    GridView3.DataBind();
                }
            }
    
            private DataTable GetSampleData()
            {
                DataTable dt = new DataTable();
                using (SqlConnection con = new SqlConnection(constr))
                {
                    string cmdtext = "select BelongsTo, ItemName, Qty from TestTable t2";
                    using (SqlCommand cmd = new SqlCommand(cmdtext, con))
                    {
                        con.Open();
                        SqlDataAdapter sda = new SqlDataAdapter(cmd);
                        sda.Fill(dt);
                        DataView dv = new DataView(dt);
                        dv.Sort = "BelongsTo ASC";
                        GridView3.DataSource = dt;
                        GridView3.DataBind();
                    }
                }
                return dt;
            }
    
            protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
                    if (Session["__dt"] == null)
                        Session["__dt"] = dt;
                    string currentNum = string.Empty;
                    string NextNum = string.Empty;
                    if (e.Row.RowIndex >= 1)
                    {
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        NextNum = dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString();
                        if (currentNum != NextNum)
                            AddTotalRow("Belongs To: " + currentNum, GetTotal(dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString()).ToString());
                    }
                    else if (e.Row.RowIndex == 0)
                    {
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        AddTotalRow("Belongs To: " + currentNum, null);
                    }
                }
                else if (e.Row.RowType == DataControlRowType.Footer)
                {
                    if (Session["__dt"] != null)
                    {
                        DataTable dt = (Session["__dt"] as DataTable);
                        AddTotalRow(null, GetTotal(dt.Rows[dt.Rows.Count - 1]["BelongsTo"].ToString()).ToString());
                    }
                }
            }
    
            private decimal GetTotal(string BelongsTo)
            {
                decimal retResult = 0;
                if (Session["__dt"] != null)
                {
                    DataTable dt = (Session["__dt"] as DataTable);
                    foreach (DataRow row in dt.Rows)
                    {
                        if (Convert.ToString(row["BelongsTo"]).Equals(BelongsTo))
                            retResult += Convert.ToDecimal(row["Qty"]);
                    }
                }
                return retResult;
            }
    
            private void AddTotalRow(string value, string Total)
            {
                if (!string.IsNullOrEmpty(Total))
                {
                    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                    row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                    row.Cells.AddRange(new TableCell[] { new TableCell() { Text = "Total: ", CssClass= "removeRightBorder" }, new TableCell() { Text = Total, CssClass = "removeLeftBorder" } });
                    GridView3.Controls[0].Controls.Add(row);
                }
                if (!string.IsNullOrEmpty(value))
                {
                    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                    row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                    row.Cells.Add(new TableCell() { ColumnSpan = 3, Text = value });
                    GridView3.Controls[0].Controls.Add(row);
                }
            }
        }
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <style>
            .removeLeftBorder {
                border-left: none;
            }
            .removeRightBorder {
                border-right: none;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
           <asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" 
                 OnRowCreated="GridView3_RowCreated"
                 EnableModelValidation="True">
                <Columns>
                    <asp:BoundField DataField="BelongsTo" Visible="false" HeaderText="BelongsTo" SortExpression="BelongsTo" />
                    <asp:BoundField DataField="ItemName" HeaderText="ItemName" SortExpression="ItemName" />
                    <asp:BoundField DataField="Qty" HeaderText="Qty" SortExpression="Qty" />
                </Columns>
            </asp:GridView>
        </form>
    </body>
    </html>



    Sunday, April 30, 2017 5:10 PM
  • User2033107836 posted

    Hello Kaushal

    Thanks for the code it works fine in my real time I'm calculating the total in 3rd column so i need to show total in the 3rd column itself only

    is that any other way to show in that particular column only

    see the screenshot it has to show total in same column only

    Tuesday, June 6, 2017 11:29 PM
  • User-1509636757 posted

    in my real time I'm calculating the total in 3rd column so i need to show total in the 3rd column itself only

    is that any other way to show in that particular column only

    see the screenshot it has to show total in same column only

    I did not understand. Do you need to show ONLY total value in third column based on the values of second column? Like this way:

    ItemName Qty Total
    Belongs to A
    Apple 1
    Lemon 8
    Mango 9
    Total 18
    Belongs to B
    Mango 6
    Orange 2
    8
    Wednesday, June 7, 2017 4:16 AM
  • User2033107836 posted
    I mean total should show in the same column pls see the screenshot which I had mark red
    Wednesday, June 7, 2017 4:50 AM
  • User-1509636757 posted

    I mean total should show in the same column pls see the screenshot which I had mark red

    Please check the last post I have done with example, that shows the total in same column only:

    Wednesday, June 7, 2017 5:00 AM
  • User2033107836 posted

    I check that code its showing in ItemName column not in Qty column

    Coz in my real time i have 4 or 5 columns so how to point total to show in the particular column 

    Wednesday, June 7, 2017 5:05 AM
  • User-1509636757 posted

    I check that code its showing in ItemName column not in Qty column

    I just removed style css and rest of the code is as it is. showing expected output:

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
           <asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" 
                 OnRowCreated="GridView3_RowCreated"
                 EnableModelValidation="True">
                <Columns>
                    <asp:BoundField DataField="BelongsTo" Visible="false" HeaderText="BelongsTo" SortExpression="BelongsTo" />
                    <asp:BoundField DataField="ItemName" HeaderText="ItemName" SortExpression="ItemName" />
                    <asp:BoundField DataField="Qty" HeaderText="Qty" SortExpression="Qty" />
                </Columns>
            </asp:GridView>
        </form>
    </body>
    </html>
        public partial class WebForm138 : System.Web.UI.Page
        {
            private string constr = "data source=.;initial catalog=NORTHWND;integrated security=SSPI";
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    DataTable dt = GetSampleData();
                    GridView3.DataSource = dt;
                    GridView3.DataBind();
                }
            }
    
            private DataTable GetSampleData()
            {
                DataTable dt = new DataTable();
                using (SqlConnection con = new SqlConnection(constr))
                {
                    string cmdtext = "select BelongsTo, ItemName, Qty from TestTable t2";
                    using (SqlCommand cmd = new SqlCommand(cmdtext, con))
                    {
                        con.Open();
                        SqlDataAdapter sda = new SqlDataAdapter(cmd);
                        sda.Fill(dt);
                        DataView dv = new DataView(dt);
                        dv.Sort = "BelongsTo ASC";
                        GridView3.DataSource = dt;
                        GridView3.DataBind();
                    }
                }
                return dt;
            }
    
            protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
                    if (Session["__dt"] == null)
                        Session["__dt"] = dt;
                    string currentNum = string.Empty;
                    string NextNum = string.Empty;
                    if (e.Row.RowIndex >= 1)
                    {
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        NextNum = dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString();
                        if (currentNum != NextNum)
                            AddTotalRow("Belongs To: " + currentNum, GetTotal(dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString()).ToString());
                    }
                    else if (e.Row.RowIndex == 0)
                    {
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        AddTotalRow("Belongs To: " + currentNum, null);
                    }
                }
                else if (e.Row.RowType == DataControlRowType.Footer)
                {
                    if (Session["__dt"] != null)
                    {
                        DataTable dt = (Session["__dt"] as DataTable);
                        AddTotalRow(null, GetTotal(dt.Rows[dt.Rows.Count - 1]["BelongsTo"].ToString()).ToString());
                    }
                }
            }
    
            private decimal GetTotal(string BelongsTo)
            {
                decimal retResult = 0;
                if (Session["__dt"] != null)
                {
                    DataTable dt = (Session["__dt"] as DataTable);
                    foreach (DataRow row in dt.Rows)
                    {
                        if (Convert.ToString(row["BelongsTo"]).Equals(BelongsTo))
                            retResult += Convert.ToDecimal(row["Qty"]);
                    }
                }
                return retResult;
            }
    
            private void AddTotalRow(string value, string Total)
            {
                if (!string.IsNullOrEmpty(Total))
                {
                    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                    row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                    row.Cells.AddRange(new TableCell[] { new TableCell() { Text = "Total: ", CssClass= "removeRightBorder" }, new TableCell() { Text = Total, CssClass = "removeLeftBorder" } });
                    GridView3.Controls[0].Controls.Add(row);
                }
                if (!string.IsNullOrEmpty(value))
                {
                    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                    row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                    row.Cells.Add(new TableCell() { ColumnSpan = 3, Text = value });
                    GridView3.Controls[0].Controls.Add(row);
                }
            }
        }



    Wednesday, June 7, 2017 7:33 AM
  • User2033107836 posted

    Hello

    Thanks For Your Code

    Let us assume i have one more column Rate i want that column total also then how would be the query please

    Wednesday, June 7, 2017 5:32 PM
  • User-1509636757 posted

    You should use the exact same logic which is used for Qty column. There is no difference.

    Wednesday, June 7, 2017 6:25 PM
  • User2033107836 posted

    Can you share me the code for Qty and Rate total so that i can understand how it works for multiple columns?

    Please

    Wednesday, June 7, 2017 6:27 PM
  • User-1509636757 posted

    Add one more parameter for RateTotal in AddRow and Total methods and follow same logic as Total:

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
           <asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" 
                 OnRowCreated="GridView3_RowCreated"
                 EnableModelValidation="True">
                <Columns>
                    <asp:BoundField DataField="BelongsTo" Visible="false" HeaderText="BelongsTo" SortExpression="BelongsTo" />
                    <asp:BoundField DataField="ItemName" HeaderText="ItemName" SortExpression="ItemName" />
                    <asp:BoundField DataField="Qty" HeaderText="Qty" SortExpression="Qty" />
                    <asp:BoundField DataField="Rate" HeaderText="Rate" SortExpression="Rate" />
                </Columns>
            </asp:GridView>
        </form>
    </body>
    </html>
        public partial class WebForm138 : System.Web.UI.Page
        {
            private string constr = "data source=.;initial catalog=NORTHWND;integrated security=SSPI";
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    DataTable dt = GetSampleData();
                    GridView3.DataSource = dt;
                    GridView3.DataBind();
                }
            }
    
            private DataTable GetSampleData()
            {
                DataTable dt = new DataTable();
                using (SqlConnection con = new SqlConnection(constr))
                {
                    string cmdtext = "select BelongsTo, ItemName, Qty, Rate from TestTable t2";
                    using (SqlCommand cmd = new SqlCommand(cmdtext, con))
                    {
                        con.Open();
                        SqlDataAdapter sda = new SqlDataAdapter(cmd);
                        sda.Fill(dt);
                        DataView dv = new DataView(dt);
                        dv.Sort = "BelongsTo ASC";
                        GridView3.DataSource = dt;
                        GridView3.DataBind();
                    }
                }
                return dt;
            }
    
            protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
                    if (Session["__dt"] == null)
                        Session["__dt"] = dt;
                    string currentNum = string.Empty;
                    string NextNum = string.Empty;
                    if (e.Row.RowIndex >= 1)
                    {
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        NextNum = dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString();
                        decimal RateTotal = 0;
                        if (currentNum != NextNum)
                            AddTotalRow("Belongs To: " + currentNum, GetTotal(dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString(), out RateTotal).ToString(), RateTotal.ToString());
                    }
                    else if (e.Row.RowIndex == 0)
                    {
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        AddTotalRow("Belongs To: " + currentNum, null, null);
                    }
                }
                else if (e.Row.RowType == DataControlRowType.Footer)
                {
                    if (Session["__dt"] != null)
                    {
                        decimal RateTotal = 0;
                        DataTable dt = (Session["__dt"] as DataTable);
                        AddTotalRow(null, GetTotal(dt.Rows[dt.Rows.Count - 1]["BelongsTo"].ToString(), out RateTotal).ToString(), RateTotal.ToString());
                    }
                }
            }
    
            private decimal GetTotal(string BelongsTo, out decimal RateTotal)
            {
                decimal retResult = 0;
                RateTotal = 0;
                if (Session["__dt"] != null)
                {
                    DataTable dt = (Session["__dt"] as DataTable);
                    foreach (DataRow row in dt.Rows)
                    {
                        if (Convert.ToString(row["BelongsTo"]).Equals(BelongsTo))
                        {
                            retResult += Convert.ToDecimal(row["Qty"]);
                            RateTotal += Convert.ToDecimal(row["Rate"]);
                        }
                    }
                }
                return retResult;
            }
    
            private void AddTotalRow(string value, string Total, string RateTotal)
            {
                if (!string.IsNullOrEmpty(Total))
                {
                    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                    row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                    row.Cells.AddRange(new TableCell[]
                    { new TableCell() { Text = "Total: "}, new TableCell() { Text = Total}, new TableCell() { Text = RateTotal} });
                    GridView3.Controls[0].Controls.Add(row);
                }
                if (!string.IsNullOrEmpty(value))
                {
                    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                    row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                    row.Cells.Add(new TableCell() { ColumnSpan = 3, Text = value });
                    GridView3.Controls[0].Controls.Add(row);
                }
            }
        }



    Thursday, June 8, 2017 6:21 AM
  • User2033107836 posted

    Thanks 

    Code Works Fine.. If no parameter

    Error Error

    if we use parameter then below error

    Object reference not set to an instance of an object.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

    Source Error:

    Line 172:                DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
    Line 173:                if (Session["__dt"] == null)
    Line 174:                    Session["__dt"] = dt;

    Thursday, June 8, 2017 9:46 AM
  • User-1509636757 posted

    It is difficult to understand what issue is here, without having knowledge of your code that you are working. I suggest you debug your code and see why DataTable is not being received at that line or post your code.

    Thursday, June 8, 2017 10:36 AM
  • User2033107836 posted

    Here Is the complete code

    <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="testing.aspx.cs" Inherits="testing" Title="Untitled Page" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
            <asp:ListItem Selected="True">Select</asp:ListItem>
            <asp:ListItem>A</asp:ListItem>
            <asp:ListItem>B</asp:ListItem>
            <asp:ListItem>C</asp:ListItem>
        </asp:DropDownList>
    <asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" 
                 OnRowCreated="GridView3_RowCreated"
                 EnableModelValidation="True">
                <Columns>
                    <asp:BoundField DataField="BelongsTo" Visible="false" HeaderText="BelongsTo" SortExpression="BelongsTo" />
                    <asp:BoundField DataField="ItemName" HeaderText="ItemName" SortExpression="ItemName" />
                    <asp:BoundField DataField="Qty" HeaderText="Qty" SortExpression="Qty" />
                    <asp:BoundField DataField="Rate" HeaderText="Rate" SortExpression="Rate" />
                </Columns>
            </asp:GridView>
    
    </asp:Content>
    
    

    Code behind

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;
    using System.Collections.Specialized;
    using System.Text;
    using System.Drawing;
    using System.IO;
    using System.Net;
    using System.Net.Mail;
    using System.Net.Configuration;
    
    public partial class testing : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }
    
        private DataTable GetSampleData()
        {
            DataTable dt = new DataTable();
            using (SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["invConnectionString"].ConnectionString))
            {
                string cmdtext = "select BelongsTo, ItemName, Qty, Rate from TestTable t2 where BelongsTo='"+DropDownList1.Text+"'";
                using (SqlCommand cmd = new SqlCommand(cmdtext, con1))
                {
                    con1.Open();
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    sda.Fill(dt);
                    DataView dv = new DataView(dt);
                    dv.Sort = "BelongsTo ASC";
                    GridView3.DataSource = dt;
                    GridView3.DataBind();
                }
            }
            return dt;
        }
    
        protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
             
                if (e.Row.RowIndex >= 1)
                {
                    DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
                    if (Session["__dt"] == null)
                        Session["__dt"] = dt;
                    string currentNum = string.Empty;
                    string NextNum = string.Empty;
                    currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                    NextNum = dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString();
                    decimal RateTotal = 0;
                    if (currentNum != NextNum)
                        AddTotalRow("Belongs To: " + currentNum, GetTotal(dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString(), out RateTotal).ToString(), RateTotal.ToString());
                }
                else if (e.Row.RowIndex == 0)
                {
                    DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
                    if (Session["__dt"] == null)
                        Session["__dt"] = dt;
                    string currentNum = string.Empty;
                    string NextNum = string.Empty;
                    currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                    AddTotalRow("Belongs To: " + currentNum, null, null);
                }
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                if (Session["__dt"] != null)
                {
                    decimal RateTotal = 0;
                    DataTable dt = (Session["__dt"] as DataTable);
                    AddTotalRow(null, GetTotal(dt.Rows[dt.Rows.Count - 1]["BelongsTo"].ToString(), out RateTotal).ToString(), RateTotal.ToString());
                }
            }
        }
    
        private decimal GetTotal(string BelongsTo, out decimal RateTotal)
        {
            decimal retResult = 0;
            RateTotal = 0;
            if (Session["__dt"] != null)
            {
                DataTable dt = (Session["__dt"] as DataTable);
                foreach (DataRow row in dt.Rows)
                {
                    if (Convert.ToString(row["BelongsTo"]).Equals(BelongsTo))
                    {
                        retResult += Convert.ToDecimal(row["Qty"]);
                        RateTotal += Convert.ToDecimal(row["Rate"]);
                    }
                }
            }
            return retResult;
        }
    
        private void AddTotalRow(string value, string Total, string RateTotal)
        {
            if (!string.IsNullOrEmpty(Total))
            {
                GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                TableCell NT = new TableCell();
                NT.ColumnSpan = 1;
                NT.BorderWidth = 2;
                NT.BackColor = ColorTranslator.FromHtml("#BA4A00");
                NT.ForeColor = System.Drawing.Color.White;
                NT.Text = "Total";
    
                TableCell QNT = new TableCell();
                QNT.ColumnSpan = 1;
                QNT.BorderWidth = 2;
                QNT.BackColor = ColorTranslator.FromHtml("#BA4A00");
                QNT.ForeColor = System.Drawing.Color.White;
                QNT.Text = Total;
                QNT.HorizontalAlign = HorizontalAlign.Right;
    
    
                TableCell YNT = new TableCell();
                YNT.ColumnSpan = 1;
                YNT.BorderWidth = 2;
                YNT.BackColor = ColorTranslator.FromHtml("#BA4A00");
                YNT.ForeColor = System.Drawing.Color.White;
                YNT.Text = RateTotal;
                YNT.HorizontalAlign = HorizontalAlign.Right;
    
                row.Cells.AddRange(new TableCell[] { NT, QNT, YNT });
                GridView3.Controls[0].Controls.Add(row);
            }
            if (!string.IsNullOrEmpty(value))
            {
                GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                TableCell ZNT = new TableCell();
                ZNT.ColumnSpan = 5;
                ZNT.BorderWidth = 2;
                ZNT.BackColor = ColorTranslator.FromHtml("#117A65");
                ZNT.ForeColor = System.Drawing.Color.White;
                ZNT.Text = value;
                row.Cells.Add(ZNT);
                GridView3.Controls[0].Controls.Add(row);
            }
        }
    
    
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataTable dt = GetSampleData();
            GridView3.DataSource = dt;
            GridView3.DataBind();
        }
    }
    

    **After page load I select A from dropdownlist it shows data perfect again if i select B from dropdownlist getting error why

    Thursday, June 8, 2017 10:46 AM
  • User-1509636757 posted

    Code Works Fine.. If no parameter

    Error Error

    if we use parameter then below error

    can you provide information on which parameter  you are talking about?

    Thursday, June 8, 2017 11:26 AM
  • User2033107836 posted

    Please see this below link

    I have share complete code 

    https://forums.asp.net/post/6143563.aspx

    Thursday, June 8, 2017 11:31 AM
  • User-1509636757 posted

    You only required to null out session before binding GridView again, check OnSelectedIndexChanged event:

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
            <asp:ListItem Selected="True">Select</asp:ListItem>
            <asp:ListItem>A</asp:ListItem>
            <asp:ListItem>B</asp:ListItem>
            <asp:ListItem>C</asp:ListItem>
        </asp:DropDownList>
            <br /><br /><br />
           <asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" 
                 OnRowCreated="GridView3_RowCreated"
                 EnableModelValidation="True">
                <Columns>
                    <asp:BoundField DataField="BelongsTo" Visible="false" HeaderText="BelongsTo" SortExpression="BelongsTo" />
                    <asp:BoundField DataField="ItemName" HeaderText="ItemName" SortExpression="ItemName" />
                    <asp:BoundField DataField="Qty" HeaderText="Qty" SortExpression="Qty" />
                    <asp:BoundField DataField="Rate" HeaderText="Rate" SortExpression="Rate" />
                </Columns>
            </asp:GridView>
        </form>
    </body>
    </html>
        public partial class WebForm138 : System.Web.UI.Page
        {
            private string constr = "data source=.;initial catalog=NORTHWND;integrated security=SSPI";
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    DataTable dt = GetSampleData();
                    GridView3.DataSource = dt;
                    GridView3.DataBind();
                }
            }
    
            protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
            {
                Session["__dt"] = null;
                DataTable dt = GetSampleData();
                GridView3.DataSource = dt;
                GridView3.DataBind();
            }
    
            private DataTable GetSampleData()
            {
                DataTable dt = new DataTable();
                using (SqlConnection con = new SqlConnection(constr))
                {
                    string cmdtext = "select BelongsTo, ItemName, Qty, Rate from TestTable t2 where BelongsTo='" + DropDownList1.Text + "'";
                   // string cmdtext = "select BelongsTo, ItemName, Qty, Rate from TestTable t2";
                    using (SqlCommand cmd = new SqlCommand(cmdtext, con))
                    {
                        con.Open();
                        SqlDataAdapter sda = new SqlDataAdapter(cmd);
                        sda.Fill(dt);
                        DataView dv = new DataView(dt);
                        dv.Sort = "BelongsTo ASC";
                        GridView3.DataSource = dt;
                        GridView3.DataBind();
                    }
                }
                return dt;
            }
    
            protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow && null != e.Row.DataItem)
                {
                    DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
                    if (Session["__dt"] == null)
                        Session["__dt"] = dt;
                    string currentNum = string.Empty;
                    string NextNum = string.Empty;
                    if (e.Row.RowIndex >= 1)
                    {
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        NextNum = dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString();
                        decimal RateTotal = 0;
                        if (currentNum != NextNum)
                            AddTotalRow("Belongs To: " + currentNum, GetTotal(dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString(), out RateTotal).ToString(), RateTotal.ToString());
                    }
                    else if (e.Row.RowIndex == 0)
                    {
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        AddTotalRow("Belongs To: " + currentNum, null, null);
                    }
                }
                else if (e.Row.RowType == DataControlRowType.Footer)
                {
                    if (Session["__dt"] != null)
                    {
                        decimal RateTotal = 0;
                        DataTable dt = (Session["__dt"] as DataTable);
                        AddTotalRow(null, GetTotal(dt.Rows[dt.Rows.Count - 1]["BelongsTo"].ToString(), out RateTotal).ToString(), RateTotal.ToString());
                    }
                }
            }
    
            private decimal GetTotal(string BelongsTo, out decimal RateTotal)
            {
                decimal retResult = 0;
                RateTotal = 0;
                if (Session["__dt"] != null)
                {
                    DataTable dt = (Session["__dt"] as DataTable);
                    foreach (DataRow row in dt.Rows)
                    {
                        if (Convert.ToString(row["BelongsTo"]).Equals(BelongsTo))
                        {
                            retResult += Convert.ToDecimal(row["Qty"]);
                            RateTotal += Convert.ToDecimal(row["Rate"]);
                        }
                    }
                }
                return retResult;
            }
    
            private void AddTotalRow(string value, string Total, string RateTotal)
            {
                if (!string.IsNullOrEmpty(Total))
                {
                    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                    row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                    row.Cells.AddRange(new TableCell[]
                    { new TableCell() { Text = "Total: "}, new TableCell() { Text = Total}, new TableCell() { Text = RateTotal} });
                    GridView3.Controls[0].Controls.Add(row);
                }
                if (!string.IsNullOrEmpty(value))
                {
                    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                    row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                    row.Cells.Add(new TableCell() { ColumnSpan = 3, Text = value });
                    GridView3.Controls[0].Controls.Add(row);
                }
            }
        }



    Thursday, June 8, 2017 11:42 AM
  • User2033107836 posted

    Oww Perfect Working Thanks Lot Mr.Kaushal

    Final and last help how to get Grand Total Like This Below In Footer

    Thursday, June 8, 2017 11:53 AM
  • User-1509636757 posted

    You should have a running total in RowCreated event.

            protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow && null != e.Row.DataItem)
                {
                    DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
                    if (Session["__dt"] == null)
                        Session["__dt"] = dt;
                    string currentNum = string.Empty;
                    string NextNum = string.Empty;
                    if (e.Row.RowIndex >= 1)
                    {
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        NextNum = dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString();
                        decimal RateTotal = 0;
                        if (currentNum != NextNum)
                            AddTotalRow("Belongs To: " + currentNum, GetTotal(dt.Rows[e.Row.RowIndex - 1]["BelongsTo"].ToString(), out RateTotal).ToString(), RateTotal.ToString());
                    }
                    else if (e.Row.RowIndex == 0)
                    {
                        currentNum = dt.Rows[e.Row.RowIndex]["BelongsTo"].ToString();
                        AddTotalRow("Belongs To: " + currentNum, null, null);
                    }
                }
                else if (e.Row.RowType == DataControlRowType.Footer)
                {
                    if (Session["__dt"] != null)
                    {
                        decimal RateTotal = 0;
                        DataTable dt = (Session["__dt"] as DataTable);
                        AddTotalRow(null, GetTotal(dt.Rows[dt.Rows.Count - 1]["BelongsTo"].ToString(), out RateTotal).ToString(), RateTotal.ToString());
    
                        decimal qtyTotal = 0;
                        decimal rateTotal = 0;
                        foreach (DataRow item in dt.Rows)
                        {
                            qtyTotal += Convert.ToDecimal(item["Qty"]);
                            rateTotal += Convert.ToDecimal(item["Rate"]);
                        }
                        GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
                        row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
                        row.Cells.AddRange(new TableCell[]
                        { new TableCell() { Text = "Grand Total: ", ForeColor = Color.Red}, new TableCell() { Text = qtyTotal.ToString(), ForeColor = Color.Red}, new TableCell() { Text = rateTotal.ToString(), ForeColor = Color.Red} });
                        GridView3.Controls[0].Controls.Add(row);
                    }
                }
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 8, 2017 12:32 PM
  • User2033107836 posted

    Thank You So Much For Your Code..

    It Works Fine..! Marked Answer.

    Thursday, June 8, 2017 2:08 PM
  • User2033107836 posted

    Thanks Lot

    Saturday, June 10, 2017 12:32 AM