Sum of DropDownList Selected Values Inside GridView Using jQuery

Task Description

We have a GridView Control containing the DropDownlist in it's TemplateField Column (ItemTemplate). Each DropDownList has some selected integer value. The sum of these selected values should display below DropDownList and should also be updated as the user changes any DropDownList selected value.

How to do it

This is done using jQuery. A class "items" is added to DropDownList. This class is further used by jQuery to find the DropDownList on the client-side. On the "document ready" and "DropDownList's change" events a method "CalculateTotal" is called, that performs the main task. Here is the code.

Code Behind

  1. using System;  
  2. using System.Collections.Generic;  
  3. public partial class _Default : System.Web.UI.Page  
  4. {  
  5.     protected void Page_Load(object sender, EventArgs e)  
  6.     {  
  7.         List<Number> list = new List<Number>();  
  8.         list.Add(new Number("1"));  
  9.         list.Add(new Number("2"));  
  10.         list.Add(new Number("3"));  
  11.         list.Add(new Number("4"));  
  12.         GridView1.DataSource = list;  
  13.         GridView1.DataBind();  
  14.     }  
  15.     public class Number  
  16.     {  
  17.         public string Num { getset; }  
  18.         public Number(string str)  
  19.         {  
  20.             this.Num = str;  
  21.         }  
  22.     }  
  23. } 

ASPX

  1. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">  
  2. <Columns>  
  3. <asp:TemplateField HeaderText="Serial Number">  
  4. <ItemTemplate>  
  5. <%# ((Number)Container.DataItem).Num %>  
  6. </ItemTemplate>  
  7. </asp:TemplateField>  
  8. <asp:TemplateField HeaderText="Values">  
  9. <ItemTemplate>  
  10. <asp:DropDownList ID="DropDownList1" runat="server"ClientIDMode="Static" CssClass="items">  
  11. <asp:ListItem>1</asp:ListItem>  
  12. <asp:ListItem>2</asp:ListItem>  
  13. <asp:ListItem>3</asp:ListItem>  
  14. <asp:ListItem>4</asp:ListItem>  
  15. </asp:DropDownList>  
  16. </ItemTemplate>  
  17. </asp:TemplateField>  
  18. </Columns>  
  19. </asp:GridView>  
  20. <br />  
  21. Total : <asp:Label ID="LabelTotal" runat="server" ClientIDMode="Static"></asp:Label>  
  22. <script>  
  23.     $(document).ready(function () {  
  24.         CalculateTotal();  
  25.         $('.items').change(function () { CalculateTotal(); });  
  26.     });  
  27.     function CalculateTotal() {  
  28.         var val = 0;  
  29.         $('.items').each(function () {  
  30.             val = val + parseFloat($(this).find('option:selected').val());  
  31.         });  
  32.         $('#LabelTotal').text(val);  
  33.         val = 0;  
  34.     }  
  35. </script>   

Output

DropDownList selected Values 


Similar Articles