Click here to Skip to main content
13,094,001 members (58,595 online)
Rate this:
 
Please Sign up or sign in to vote.
how to calculate sum of gridview columns in .net.can any one help
Posted 21-Oct-11 0:44am
Updated 8-May-17 21:39pm
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 4

try this way..

 
decimal a=0, b=0, c=0;
 
for (int i = 0; i < (gridview1.Rows.Count); i++)
           {
               a = Convert.ToDecimal(gridview1.Rows[i].Cells["Column Index"].Text.ToString());
               c = c + a; //storing total qty into variable 
}


For more info.. u can visit link below...

http://midotnetexp.blogspot.in/#!/2012/06/how-to-calculate-sum-of-gridview.html[^]


hope this help u..
  Permalink  
v5
Comments
supriya chaladi 22-Oct-11 1:49am
   
my vote of 5
Dev.Vikas.S 23-Oct-11 9:27am
   
thanx
lighthousekeeper 27-Aug-12 16:00pm
   
thx!
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Hi,

In server side or client side

If it in server side check this once

 int sm=0;
  foreach(GridRow gr in GridView1.Rows)
{
   sm+=int.parse(gr[coumnindex].Text);//if it has only text
  sm+=int.parse(((Control)gr[columnindex].findcontrol("controlid")).Text);
}


This is just for idea

All the Best
  Permalink  
Comments
ravisonaiya 25-Sep-12 2:32am
   
hi there,
Its good but its not giving the total value of the columns.
ravisonaiya 25-Sep-12 2:35am
   
hey never mind my first comment.
its work fine for me now. i have done very small change in your code and you known what now its giving a perfect result.
thanks
Muralikrishna8811 25-Sep-12 6:05am
   
Hi Ravisonaiya,
Let me know What changes are need to be done to make it perfect I'll Update my solution
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 5

Replace Cells values as per your requirement.

((Label)GVDailyTimeSheet.FooterRow.Cells[3].FindControl("lblTotalHours")).Text = dt.Compute("sum(Hours)", "").ToString();
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 6

To calculate the sum of a column in a DataTable use the DataTable Compute[^]method.

Example of usage from the linked MSDN article:
DataTable table;
table = dataSet.Tables["YourTableName"];
 
// Declare an object variable.
object sumObject;
sumObject = table.Compute("Sum(Amount)", "");

Display the result in your Total Amount Label like so:
labelTotalAmount.Text = sumObject.ToString();
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 7

i show u an example...this will be essier

javascript funtion; you just change the gridview name

function CalculateTotals()
 {
            var gv = document.getElementById("<%= gvPO.ClientID %>");
            var tb = gv.getElementsByTagName("input");
            var lb = gv.getElementsByTagName("span");
 
            var sub = 0;
            var total = 0;
            var indexQ = 1;
            var indexP = 0;
            var price = 0;
            var qty = 0;
            var totalQty = 0;
            var tbCount = tb.length / 2;
 
            for (var i = 0; i < tbCount; i++)
            {
 
                if (tb[i].type == "text") {
                    ValidateNumber(tb[i + indexQ]);
 
                    sub = parseFloat(tb[i + indexP].value) * parseFloat(tb[i + indexQ].value);
 
                    if (isNaN(sub)) {
                        lb[i].innerHTML = "0.00";
                        sub = 0;
                    }
                    else {
                        lb[i].innerHTML = FormatToMoney(sub, " ", ",", "."); ;
                    }
 
                    if (isNaN(tb[i + indexQ].value) || tb[i + indexQ].value == "") {
                        qty = 0;
                    }
                    else {
                        qty = tb[i + indexQ].value;
                    }
 
                    totalQty += parseInt(qty);
                    total += parseFloat(sub);
 
                    indexQ++;
                    indexP++;
                }
            }
 
            lb[lb.length - 2].innerHTML = totalQty;
            lb[lb.length -1].innerHTML = FormatToMoney(total, " ", ",", ".");
        }






<asp:GridView ID="gvPO" runat="server" AutoGenerateColumns="False"
                    CellPadding="4" GridLines="None"  ShowFooter="True" DataKeyNames="ITEMCODE"
                    Width="776px"  Height="167px"
 
                    ForeColor="#333333"
                      onrowdeleting="gvPO_RowDeleting" ondatabound="gvPO_DataBound"
                     onprerender="gvPO_PreRender" onrowdatabound="gvPO_RowDataBound"
 

                   >
                    <FooterStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
                    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
                   <Columns>
 
                       <asp:BoundField DataField="ITEMCODE" HeaderText="Item Code"
                           SortExpression="ITEMCODE" />
                             <asp:BoundField DataField="ITEMDESCRIPTION" HeaderText="Description"
                           SortExpression="ITEMDESCRIPTION" />
 

                       <asp:TemplateField HeaderText="Qty">
        <ItemTemplate>
            <asp:Label ID="lblQty" runat="server" Text='<%# Eval("OPENINGQTY")%>' ></asp:Label>
         </ItemTemplate>
         <FooterTemplate>
             <asp:Label ID="lblTotalqty" runat="server" Text="0"></asp:Label>
         </FooterTemplate>
         </asp:TemplateField>
 
          <asp:BoundField DataField="ITEMUNIT" HeaderText="UOM"
                           SortExpression="ITEMUNIT" />
 
         <asp:TemplateField HeaderText="Rate">
        <ItemTemplate>
            <asp:Label ID="lblPrice" runat="server" Text='<%# Eval("PURCHASERATE")%>' ></asp:Label>
         </ItemTemplate>
 
      </asp:TemplateField>
 

       <asp:TemplateField HeaderText="Value">
        <ItemTemplate>
            <asp:Label ID="lbltotal" runat="server" Text='<%# Eval("SUBTOTAL")%>' ></asp:Label>
         </ItemTemplate>
        <FooterTemplate>
        <asp:Label ID="lblSubtotal" runat="server" Text="0.00"></asp:Label>
        </FooterTemplate>
      </asp:TemplateField>
 
      <asp:TemplateField HeaderText="VAT %">
        <ItemTemplate>
            <asp:Label ID="lblVATpercentage" runat="server" Text='<%# Eval("VatPercentage")%>' ></asp:Label>
         </ItemTemplate>
      </asp:TemplateField>
 
      <asp:TemplateField HeaderText="VAT Total">
        <ItemTemplate>
            <asp:Label ID="lblVATtotal" runat="server" Text='<%# Eval("VatTotal")%>' ></asp:Label>
         </ItemTemplate>
        <FooterTemplate>
        <asp:Label ID="lblVATtotal" runat="server" Text="0.00"></asp:Label>
        </FooterTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="Total Amount">
        <ItemTemplate>
            <asp:Label ID="lbltotalAmount" runat="server" Text='<%# Eval("TotalAmount")%>' ></asp:Label>
         </ItemTemplate>
        <FooterTemplate>
        <asp:Label ID="lbltotalAmount" runat="server" Text="0.00"></asp:Label>
        </FooterTemplate>
      </asp:TemplateField>
 

 

         <asp:TemplateField >
     <ItemTemplate>
       <asp:LinkButton ID="LinkButton1"
         CommandArgument='<%# Eval("ITEMCODE") %>'
         CommandName="Delete" runat="server" OnClientClick="javascript:return confirm('Do you really want to \ndelete the item?');">
         Delete</asp:LinkButton>
     </ItemTemplate>
   </asp:TemplateField>
 
         </Columns>
                <RowStyle CssClass="RowStyle" />
 
   <PagerStyle CssClass="PagerStyle" />
 
    <SelectedRowStyle CssClass="SelectedRowStyle" />
 
    <HeaderStyle CssClass="HeaderStyle" />
 
    <EditRowStyle CssClass="EditRowStyle" />
 
    <AlternatingRowStyle CssClass="AltRowStyle" />
 
                   </asp:GridView>



protected void gvPO_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType ==DataControlRowType.EmptyDataRow)
{
grdTotal = 0;
grdQty = 0;
grdVat = 0;
grdAmount = 0;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{

int Qty = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "OPENINGQTY"));
decimal SubTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "SUBTOTAL"));
decimal vat = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "VatTotal"));
decimal TotalAmount = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "TotalAmount"));

grdQty = grdQty + Qty;
grdTotal = grdTotal + SubTotal;
grdVat = grdVat + vat;
grdAmount = grdAmount + TotalAmount;


}

if (e.Row.RowType == DataControlRowType.Footer)
{

Label lbl = (Label)e.Row.FindControl("lblTotalqty");
lbl.Text = grdQty.ToString();


Label lb2 = (Label)e.Row.FindControl("lblSubtotal");
lb2.Text = grdTotal.ToString();

Label lb3 = (Label)e.Row.FindControl("lblVATtotal");
lb3.Text = grdVat.ToString();

Label lb4 = (Label)e.Row.FindControl("lbltotalAmount");
lb4.Text = grdAmount.ToString();


txtTotal.Text = grdAmount.ToString();
total = ConvertToINR(txtTotal.Text).ToString();
txtAmountInWords.Text = total.ToString();
}
}
catch (Exception)
{
// Response.Write("<script language='javascript'>alert('Data Table is null...');</script>");

}
}

i hope now you can do it.... All the very best......
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 8

public string GetGross()
        {
            decimal Gross = 0;
            if (dgvItem.Rows.Count > 0)
            {
                for (int i = 0; i < dgvItem.Rows.Count; i++)
                {
                    Gross = Gross + Convert.ToDecimal(((Label)dgvItem.Rows[i].FindControl("lblAmount")).Text.ToString());
                }
 
            }
            return Gross.ToString();
        }
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 9

Best Answer - SINGLE LINE
 
    <asp:TemplateField HeaderText="Net Amt">
        <ItemTemplate>    
    <%# (Eval("itm_or_fee_amt")==DBNull.Value?0:Convert.ToDouble(Eval("itm_or_fee_amt")))+(Eval("late_fee")==DBNull.Value?0:Convert.ToDouble(Eval("late_fee"))) %>
     </ItemTemplate>  
     </asp:TemplateField>
  Permalink  
Comments
CHill60 21-Dec-15 4:28am
   
Hardly the best answer as it's unreadable and 4 years late
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 10

public decimal ff_Calculate_Tot()
       {
               decimal ldec_grd_tot = 0;
               if (grd_rev_dtls.Rows.Count > 0)
               {
                   if (ff_check() == true)
                   {
                       for (int i = 0; i < grd_rev_dtls.Rows.Count; i++)
                       {
                           decimal ld_tot = 0;
                           bool isChecked_Short;
                           GridViewRow row = grd_rev_dtls.Rows[i];
                           if (isChecked_Short = ((CheckBox)row.FindControl("chk_pay")).Checked)
                           {
                               ld_tot = Convert.ToDecimal(((TextBox)row.FindControl("txt_earn")).Text);
                           }
                           ldec_grd_tot = ldec_grd_tot + ld_tot;
                       }
                   } 
               }
               return ldec_grd_tot;
           }
 
       }



txt_earn is the textbox in gridview

<asp:TextBox ID="txt_earn" runat="server" Text='<%# Eval("amount") %>'></asp:TextBox>
  Permalink  
Comments
CHill60 22-Dec-15 3:06am
   
Question was asked and answered over 4 years ago. Even if you didn't notice the date, the fact there were already 8 solutions should have suggested to you that posting this was pointless
Jiyaji_ 22-Dec-15 7:42am
   
i didn't notice the date..iam not writing here to get points...
CHill60 22-Dec-15 8:27am
   
By "pointless" I meant "not worth the effort", "senseless"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy |
Web01 | 2.8.170813.1 | Last Updated 9 May 2017
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100