Sum UP value from odd column in gridview. RRS feed

  • Question

  • User929636964 posted


    I'm using one pivot query in SP to display data in gridview. The pivot query display dynamic date into column.

    The problem is, how I want to add one column(SUM TQ) to sum up column no 8, 11, 14.....(multiples 3). if I want to use gridview rowdatabound.


    Wednesday, November 28, 2018 6:07 AM

All replies

  • User-893317190 posted

    Hi munirah-malik1,

    If you want to use rowdatabound to sum up several columns,you could refer to the code below.

     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">
                    <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
                    <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" SortExpression="QuantityPerUnit" />
                    <asp:TemplateField HeaderText="UnitPrice">
                            <asp:Label ID="UnitPrice" runat="server" Text='<%# Eval("UnitPrice") %>'></asp:Label>
                    <asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />

    Code behind.

     protected void Page_Load(object sender, EventArgs e)
                if (!IsPostBack)
                    using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT [ProductName], [QuantityPerUnit], [UnitPrice], [UnitsInStock] FROM [Products]", constr))
                        DataTable table = new DataTable();
                        //add a new column to show the sum
                        GridView1.Columns.Add( new BoundField
                            HeaderText = " (dynamic)",
            protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
                if (e.Row.RowType == DataControlRowType.DataRow)
                    Label label = e.Row.FindControl("UnitPrice") as Label;
                    double unitPrice = Double.Parse(label.Text);   //if you use template, please get the control which contains the value and the then get the value.
                    int unitInStock = int.Parse(e.Row.Cells[3].Text);//if you use boundfield , please use e.Row.Cells[index].Text to get the value
                    e.Row.Cells[4].Text = (unitPrice + unitInStock).ToString();

    The result.

    Best regards,

    Ackerly Xu

    Thursday, November 29, 2018 4:38 AM