You must Sign In to post a response.
  • Category: ASP.NET

    How to caluculate total from quantity and price in gridview for each row

    Hi,

    iam using

    int newprice = dt.AsEnumerable().Sum(row => row.Field<int>("Price"));
    int newqty = dt.AsEnumerable().Sum(row => row.Field<int>("Quantity"));
    int subtotal = newprice * newqty;

    this will be give output wrong where i can change my code.
  • #762482
    Hi

    You can follow this code for caluculate total from quantity and price in gridview for each row

    Client Side Code



    <asp:GridView ID="Grd1" runat="server" AutoGenerateColumns="false" OnRowDataBound="Grd1_RowDataBound">
    <Columns>
    <asp:TemplateField HeaderText="ProductName">
    <ItemTemplate>
    <asp:Label ID="lblName" runat="server" Text='<%#Eval("ProductName") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Qty">
    <ItemTemplate>
    <asp:Label ID="lblQty" runat="server" Text='<%#Eval("Qty") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Rate">
    <ItemTemplate>
    <asp:Label ID="lblRate" runat="server" Text='<%#Eval("Rate") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Total">
    <ItemTemplate>
    <asp:Label ID="lblTotal" runat="server" Text='<%#Eval("Total") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>

    </Columns>
    </asp:GridView>



    Server Side Code C#

    Bind Records to Gridview


    DataTable dt = new DataTable();
    dt.Columns.Add("ProductName");
    dt.Columns.Add("Qty");
    dt.Columns.Add("Rate");
    dt.Columns.Add("Total");

    DataRow dr;
    dr=dt.NewRow();
    dr[0] = "Mouse";
    dr[1] = 10;
    dr[2] = 300;
    dr[3] = 0;
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0] = "Optical Mouse";
    dr[1] = 10;
    dr[2] = 600;
    dr[3] = 0;
    dt.Rows.Add(dr);

    Grd1.DataSource = dt;
    Grd1.DataBind();



    Calculate the Gridview Records




    protected void Grd1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
    for (int i = 0; i < Grd1.Rows.Count; i++)
    {
    Label lblTotal = (Label)Grd1.Rows[i].Cells[1].FindControl("lblTotal");
    Label lblQty = (Label)Grd1.Rows[i].Cells[1].FindControl("lblQty");
    Label lblRate = (Label)Grd1.Rows[i].Cells[1].FindControl("lblRate");
    decimal total = Convert.ToDecimal(lblQty.Text) * Convert.ToDecimal(lblRate.Text);
    lblTotal.Text = total.ToString();
    }
    }





    I have attached Snapshot given below.

    Name : Dotnet Developer-2015
    Email Id :kumaraspcode2009@gmail.com

    'Not by might nor by power, but by my Spirit,' says the LORD Almighty.

    Delete Attachment


Sign In to post your comments