Grid View Column Total in ASP.net using JQuery


Here is .aspx code:

    <div>
    <asp:GridView ID="gvSumofColumn" runat="server" AutoGenerateColumns="false">
    <Columns>
    <asp:TemplateField>
    <ItemTemplate><asp:CheckBox ID="Check" runat="server" /></ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField>
    <ItemTemplate> <%#Eval("Product")%> </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField>
    <ItemTemplate> <%#Eval("Price")%> </ItemTemplate>
    </asp:TemplateField>

    </Columns>
    </asp:GridView>

    <p id="total"></p>

    </div>


Here is the Script (JQuery) on top of the page in
<script language="javascript" type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script language="javascript" type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>

   <script language="javascript" type="text/javascript">

        $(document).ready(function () {

            var checked = $('input:checkbox').click(function (e) {

                Total(3);

            });

            function Total(colIndx) {
                total = 0.0;
                $("tr:has(:checkbox:checked) td:nth-child(" + colIndx + ")").each(function () {
                    total += parseFloat($(this).text());
                });

                $('#total').text("Total Amount is" + total.toFixed(2));

            }
        });

    </script>

Here is .aspx.cs Code:
First Create DataTable to Bind GridView
  protected void BindGridViewTotal()
    {
     
  DataTable dt = new DataTable();
        dt.Columns.Add("Product", typeof(string));
        dt.Columns.Add("Price", typeof(double));

        for (int i = 0; i < 5; i++)
        {
            DataRow dr = dt.NewRow();
            dr["Product"] = "A" + i + 1;
            dr["Price"] = 15 + i + 1;
            dt.Rows.Add(dr);
        }

            
  gvSumofColumn.DataSource = dt;
        gvSumofColumn.DataBind();
    }

Bind the GridView on page load Event as below:
  if (!IsPostBack)
        {
BindGridViewTotal();
        }

I hope you will enjoy the topic.
Cheers.

Comments