Click here to Skip to main content
15,438,202 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Found this excellent example of how to total a gridview row online.
Just need help in adapting it to my solution.

I'm guessing the problem lies with the line "#GridView1 span[id*='lblTotal']"
as this was the only real change I made from the original code.

Code below:

JavaScript
<script language="javascript" type="text/javascript">
     function calculate() {
     var Amount = 0;
     $("#GridView1 span[id*='lblTotal']").each(function (index) {
     //Check if number is not empty
     if ($.trim($(this).val()) != "")
     //Check if number is a valid integer
         if (!isNaN($(this).val()))
             Amount = Amount + parseFloat($(this).val());
 });
       $("#GridView1 span[id*='lblTotalAmount']").text(Amount);        }
  </script>


Mark up below:

ASP.NET
 <asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" 
            DataSourceID="AccessDataSource1" 
            ShowFooter="True" style="margin-bottom: 0px">
            <Columns>
            <asp:TemplateField HeaderText="Devices And Services" Visible="True" HeaderStyle-HorizontalAlign="Left"  FooterText="Payable monthly in advance (excluding Agreement items):" ItemStyle-BackColor="#CCCCCC">
                    <ItemTemplate>
                        <asp:Label ID="lblItemDescription" runat="server" Width="382"
Text='<%# Eval("itemDescription") %>'></asp:Label>
                    </ItemTemplate>

<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Rate">
                    <ItemTemplate>
                        <asp:Label ID="lblRate" runat="server" width="50" ></asp:Label>
                       
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Number" ControlStyle-BackColor="#FFFFCC">
                    <ItemTemplate>
                        <asp:TextBox ID="txtBoxNumber" Width="100px"
runat="Server"  />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Total" ItemStyle-CssClass="total">
                    <ItemTemplate>                  
                        <asp:Label ID="lblTotal" runat="Server"  Width="106"  />
                    </ItemTemplate>
                    <FooterTemplate>
                          
                 <asp:Label ID="lblTotalAmount" runat="server"  />        
                
                    </FooterTemplate>
                </asp:TemplateField>
              
               
                  
                    
                
            </Columns>
            <FooterStyle Font-Bold="True" />
        </asp:GridView>


In my solution my lblTotal is calculated through Javascript

Code Below:

JavaScript
<script type="text/javascript">

    function multiply(Rate, number, total) {
        
        var grid = document.getElementById('GridView1');      
        var num = parseFloat(document.getElementById(number).value);
        var tot = document.getElementById(total);
      
        var totValue = parseFloat(((Rate * num)));
        var totValueRound = Math.round(totValue);
        var totValueRound = totValue;
        tot.innerHTML =  totValue.toFixed(2);
        calculate();
       
    }
<script/> 
Posted
Updated 27-May-18 22:07pm
Comments
Herman<T>.Instance 9-Feb-12 3:28am     CRLF
'I'm guessing the problem lies with the line "#GridView1 span[id*='lblTotal']"' well guess what. How can we help you now? IS there any error/exception you run into?
Andrew Chambers 9-Feb-12 4:29am     CRLF
no error to speak of. can you see anything here digimanus? Let's work to help developers, not make them feel stupid.

You're on the right track:

<asp:gridview id="GridView1" xmlns:asp="#unknown"></asp:gridview>


Does not equal

$("#GridView1


Asp.NET ID's are <> Client Side DOM IDs. You need to pass the value of the gridview's clientid property to your javascript.

One way would be (assuming your script is in the .aspx page, and not an include script):

<script language="javascript" type="text/javascript">
      function calculate() {
      var Amount = 0;
      $("#<%=GridView1.ClientID%> span[id*='lblTotal']").each(function (index) {
      //Check if number is not empty
      if ($.trim($(this).val()) != "")
      //Check if number is a valid integer
          if (!isNaN($(this).val()))
              Amount = Amount + parseFloat($(this).val());
  });
        $("#<%=GridView1.ClientID%> span[id*='lblTotalAmount']").text(Amount);        }
   </script>


Hope that gives you some ideas anyway.%>
 
Share this answer
 
v2
Comments
Martin Arapovic 9-Feb-12 4:18am    
Yes! That is the right way to use jquery with asp.net server controls.ClientId can also be set explicitly if asp.net 4.0 or higher is used... :)
Steve Echols 9-Feb-12 4:26am    
True, true. ClientIDMode="Static" or ClientIDMode="Predictable" would make it work in 4.0. Is that correct?
Martin Arapovic 9-Feb-12 11:30am    
Yes it is! ClientIDMode="Static" will do the job, but using ClientIDMode="Predictable", not exaclty. Generated Id will have NamingContainer name as prefix I think. The good thing is that, if you use jquery (javascript) a lot, ClientIDMode can be controlled at page (in page declerative) or global level (web.config pages section)...
Andrew Chambers 9-Feb-12 4:27am     CRLF
Thanks for this. I've tried the code as you have written to no avail. I have also attached a class to both lblTotal and lblTotalAmount. $(".total").each(function (index)and $(".totallabel").text(Amount); to no avail.Any other ideas?Cheers
Steve Echols 9-Feb-12 4:44am     CRLF
I'm thinking the lblTotal/lblTotalAmount ids are probably not what you think they are. Maybe try: <pre>$("#<%=GridView1.ClientID%> .total").each ......</pre> But basically, view the source of the page and see what the structure of the elements are and what pattern you'd need to use as your selectors for jQuery (I'm not a jQuery expert, I use prototype.js)
protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Item"), new DataColumn("Price") });
        dt.Rows.Add("Shirt", 200);
        dt.Rows.Add("Football", 30);
        dt.Rows.Add("Bat", 22.5);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }



    <title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=txtQuantity]").val("0");
    });
    $("[id*=txtQuantity]").live("change", function () {
        if (isNaN(parseInt($(this).val()))) {
            $(this).val('0');
        } else {
            $(this).val(parseInt($(this).val()).toString());
        }
    });
    $("[id*=txtQuantity]").live("keyup", function () {
        if (!jQuery.trim($(this).val()) == '') {
            if (!isNaN(parseFloat($(this).val()))) {
                var row = $(this).closest("tr");
                $("[id*=lblTotal]", row).html(parseFloat($(".price", row).html()) * parseFloat($(this).val()));
            }
        } else {
            $(this).val('');
        }
        var grandTotal = 0;
        $("[id*=lblTotal]").each(function () {
            grandTotal = grandTotal + parseFloat($(this).html());
        });
        $("[id*=lblGrandTotal]").html(grandTotal.toString());
    });
</script>



 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="Item" HeaderText="Item" />
            <asp:BoundField DataField="Price" HeaderText="Price" ItemStyle-CssClass="price" >
<ItemStyle CssClass="price"></ItemStyle>
            </asp:BoundField>
            <asp:TemplateField HeaderText = "Quantity">
                <ItemTemplate>
                    <asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText = "Total">
                <FooterTemplate>
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblTotal" runat="server" Text="0"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#99CCFF" />
    </asp:GridView>
    Grand Total:
    <asp:Label ID="lblGrandTotal" runat="server" Text="0"></asp:Label>
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900