locked
using datatables.net's tools to build responsive gridview and caculate column on it RRS feed

  • Question

  • User-475949336 posted

    Dear friends!

    I'm using datatables.net's tools to build responsive gridview,
    all everything display good on mobile, laptop.
    Now, I'm facing with problem is caculate of columns in gridview2.


    I want when I change value in one of columns:

    - Change dropdownList Benefit then column 'Benefit' changed instant

    - change Salary1 OR Salary2 (Salary12 will change instant) OR change Salary12 OR Divide(3) OR Benefit (4) OR 'REMOVE ROW' OR 'add row'
    then Received=(1+2)/3+4 AND 'Total Received' will be changed instant.

    I WANT ALL changed instant (as using jquery), 'Total Received' must be textbox outside gridview2.

    Any body can helpme.
    this is my lasted code:

    Main.master
    
    <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Main.master.cs" Inherits="Quanlynhachothue.Main" %>
    
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta name="viewport" content="width = device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
        
    <title></title>
    
      <link rel="stylesheet" href='http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css' media="screen" /> 
    
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
        
          
       <script type="text/javascript" src='http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js'></script>
        
     
      <link rel="stylesheet" type="text/css" href="./css-js-Gridview/datatables.min-1.10.20.css" />      
      <script type="text/javascript" src="./css-js-Gridview/datatables.min-1.10.20.js"></script> 
                    
    
      <style type="text/css">            
         
        @media (max-width: 992px) {
        .navbar-header {
            float: none;        
        }
        .navbar-left,.navbar-right {
            float: none !important;
        }
        .navbar-toggle {
            display: block;
            
        }
        .navbar-collapse {
            border-top: 1px solid transparent;
            box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);        
            
        }
        .navbar-fixed-top {
            top: 0;
            border-width: 0 0 1px;        
        }
        .navbar-collapse.collapse {
            display: none!important;        
        }
        .navbar-nav {
            float: none!important;
            margin-top: 7.5px;
            
        }
        .navbar-nav>li {
            float: none;        
        }
        .navbar-nav>li>a {
            padding-top: 10px;
            padding-bottom: 10px;        
        }
        .collapse.in{
            display:block !important;
            
        }
    }
    
            .dropdown-submenu
            {
                ;
            }
            .dropdown-submenu > .dropdown-menu
            {
                top: 0;
                left: 100%;
                margin-top: -6px;
                margin-left: -1px;
                -webkit-border-radius: 0 6px 6px 6px;
                -moz-border-radius: 0 6px 6px 6px;
                border-radius: 0 6px 6px 6px;
                
            }
            .dropdown-submenu > a:after
            {
                display: block;
                content: " ";
                float: right;
                width: 0;
                height: 0;
                border-color: transparent;
                border-style: solid;
                border-width: 5px 0 5px 5px;
                border-left-color: #cccccc;
                margin-top: 5px;
                margin-right: -10px;            
            }
            .dropdown-submenu:hover > a:after
            {
                border-left-color: #555;
                
            }
            .dropdown-submenu.pull-left
            {
                float: none;
                
            }
            .dropdown-submenu.pull-left > .dropdown-menu
            {
                left: -100%;
                margin-left: 10px;
                -webkit-border-radius: 6px 0 6px 6px;
                -moz-border-radius: 6px 0 6px 6px;
                border-radius: 6px 0 6px 6px;            
            }
        </style>
    
        <asp:ContentPlaceHolder ID="head" runat="server">
        </asp:ContentPlaceHolder>       
    
    </head>
    <body>   
        <form id="main"  runat="server">   
      
        <div class="navbar navbar-default" style="font-family:Arial; background-color: #0066CC">
            <div class="container-fluid" style="font-family:Arial">
                <div class="navbar-header" style="font-family:Arial">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"
                        aria-expanded="false">
                        <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span><span
                            class="icon-bar"></span><span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="./">ASP</a>
                </div>
                <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" style="font-family:Arial;background-color: #1A8CFF" >
                    <asp:Menu ID="Menu1" runat="server" Orientation="Horizontal"
                     
                     RenderingMode="List" IncludeStyleBlock="false" StaticMenuStyle-CssClass="nav navbar-nav" DynamicMenuStyle-CssClass="dropdown-menu">
    
                    </asp:Menu>
                </div>
            </div>
        </div>
      <script type="text/javascript">
            Sys.WebForms.Menu._elementObjectMapper.getMappedObject = function () {
                return false;
            };
            $(function () {
                $(".navbar-nav li, .navbar-nav a, .navbar-nav ul").removeAttr('style');
                $(".dropdown-menu").closest("li").removeClass().addClass("dropdown-toggle");
                $(".dropdown-toggle").find("a[href='javascript:;']").attr("data-toggle", "dropdown");
                $(".dropdown-toggle").find("a[href='javascript:;'].level1").append("<span class='caret'></span>");
                $(".dropdown-toggle").find("a[href='javascript:;']:not(.level1)").closest('li').addClass('dropdown-submenu');
                $("a.selected").closest("li").addClass("active");
                $("a.selected").closest(".dropdown-toggle").addClass("active");
                $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    $(this).parent().siblings().removeClass('open');
                    $(this).parent().toggleClass('open');
                });
            });
        </script>
        <hr />
            
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">        
        </asp:ContentPlaceHolder>        
        </form>
    </body>
    </html>
    
    Main.master.cs
    
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace Quanlynhachothue
    {
        public partial class Main : System.Web.UI.MasterPage
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!this.IsPostBack)
                {
                      DataTable dt = this.GetData(0);
                      PopulateMenu(dt, 0, null);               
                }
            }
                    
            private DataTable GetData(int parentMenuId)
            {
                
    
                DataTable dt = new DataTable();
                dt.Columns.AddRange(new DataColumn[4] {
                new DataColumn("ParentMenuId"),
                new DataColumn("MenuId"),
                new DataColumn("Title"),
                new DataColumn("Url") });
    
    
                dt.Rows.Add(0, 1, "Home", "~/CS.aspx");
                dt.Rows.Add(0, 2, "Services", "javascript:;");
                dt.Rows.Add(0, 3, "About", "javascript:;");
                dt.Rows.Add(0, 4, "Contact ", "~/frmtabcontrolHoadonDichvu.aspx");
                dt.Rows.Add(2, 5, "Consulting", "~/Consulting.aspx");
                dt.Rows.Add(2, 6, "Outsourcing ", "~/Outsourcing.aspx");
                dt.Rows.Add(3, 7, "About1", "javascript:;");
                dt.Rows.Add(3, 8, "About2", "~/About2.aspx");
                dt.Rows.Add(7, 9, "About11", "~/About11.aspx");
                dt.Rows.Add(7, 10, "About12", "~/About12.aspx");
    
    
                DataTable dtFinal = dt.Clone();
                DataRow[] dr = dt.Select("ParentMenuId=" + parentMenuId);
                if (dr.Length > 0)
                {
                    dtFinal = dr.CopyToDataTable();
                }
    
                return dtFinal;            
            }
            
    
            private void PopulateMenu(DataTable dt, int parentMenuId, MenuItem parentMenuItem)
            {
                string currentPage = Path.GetFileName(Request.Url.AbsolutePath);
                foreach (DataRow row in dt.Rows)
                {
                    MenuItem menuItem = new MenuItem
                    {
                        Value = row["MenuId"].ToString(),
                        Text = row["Title"].ToString(),
                        NavigateUrl = row["Url"].ToString(),
                        Selected = row["Url"].ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase)
                    };
                    if (parentMenuId == 0)
                    {
                        Menu1.Items.Add(menuItem);
                        DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
                        PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
                    }
                    else
                    {
                        parentMenuItem.ChildItems.Add(menuItem);
                        if (parentMenuId > 0)
                        {
                            DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
                            PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
                        }
                    }
                }
            }
           
        }
    }
    
    CS.aspx

    <%@ Page Title="" Language="C#" MasterPageFile="~/Main.master" UnobtrusiveValidationMode="None" EnableEventValidation="false" AutoEventWireup="true" CodeBehind="CS.aspx.cs" Inherits="Quanlynhachothue.CS" %>
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>

    <asp:Content id="Content1" ContentPlaceHolderID="head" Runat="Server">

    </asp:Content>

    <asp:Content id="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

    <asp:UpdatePanel id="UpdatePanel1" runat="server">
    <ContentTemplate>

    <div class="tab-content" style="width: auto; border:none; font-family:Arial; font-size:larger; color:#1443AB; font-weight:bold; text-align:center; padding: 1px; margin: 1px">
    GRIDVIEW
    </div>
    <div class="panel panel-default" style="width: auto; padding: 6px; margin: 6px">

    <div id="dvTab">

    <ul class="nav nav-tabs" role="tablist" style="font-weight: bold">
    <li runat="server" id="idListtab" class="active"><a href="#Listtab" style="outline:none" aria-controls="Listtab" role="tab" data-toggle="tab">LIST</a></li>
    <li runat="server" id="idAddnewtab"><a href="#Addnewtab" style="outline:none" aria-controls="Addnewtab" role="tab" data-toggle="tab">ADD NEW</a></li>
    <li runat="server" id="idEdittab"><a href="#Edittab" style="outline:none" aria-controls="Edittab" role="tab" data-toggle="tab">EDIT</a></li>
    <li runat="server" id="idViewtab"><a href="#Viewtab" style="outline:none" aria-controls="Viewtab" role="tab" data-toggle="tab">VIEW</a></li>

    </ul>

    <div class="tab-content" style="padding-top: 5px">

    <!-- Begin List -->
    <div role="tabpanel" class="tab-pane active" id="Listtab">

    <div>

    <asp:ScriptManager id="toolScriptManageer1" runat="server" EnablePartialRendering="false">
    </asp:ScriptManager>

    <label for="tungay">From &nbsp;&nbsp;&nbsp;
    <asp:TextBox id="txtTungay" width="128px" Height ="30px" runat="server" MaxLength="10" AutoPostBack="true" ></asp:TextBox>
    <ajaxToolkit:CalendarExtender id="Calendarfromdate" popupbuttonid="imgPopup" runat="server" targetcontrolid="txtTungay" format="dd/MM/yyyy" />
    </label>


    <label for="denngay">To &nbsp;

    <asp:TextBox id="txtDenngay" width="128px" Height ="30px" AutoPostBack="true" runat="server" MaxLength="10" ></asp:TextBox>
    <ajaxToolkit:CalendarExtender id="Calendartodate" popupbuttonid="imgPopup" runat="server" targetcontrolid="txtDenngay" format="dd/MM/yyyy" />

    </label>

    <label for="trangthai">Status&nbsp;
    <asp:DropDownList id="txtTrangthai" width="128px" Height ="30px" AutoPostBack="true" runat="server" >
    <asp:ListItem Text="All" Value="All"></asp:ListItem>
    <asp:ListItem Text="status1" Value="1"></asp:ListItem>
    <asp:ListItem Text="status2" Value="2"></asp:ListItem>
    </asp:DropDownList>
    </label>

    </div>
    <br/>

    <asp:GridView id="GridView1" CssClass="dt-responsive" class="display" Width="100%" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#BED7F3" HeaderStyle-Height="30px" HeaderStyle-BorderStyle="None" HeaderStyle-ForeColor="#144383" Font-Names="Arial" HeaderStyle-Font-Size="13px" >

    <Columns>
    <asp:BoundField DataField="Id" HeaderText="Customer Id" />
    <asp:BoundField DataField="Name" HeaderText="Customer Name" />
    <asp:BoundField DataField="Country" HeaderText="Country" />

    <asp:TemplateField HeaderText="Salary" >
    <ItemTemplate>
    <asp:textbox ID="txtSalary" Text='<%# Eval("Salary") %>' Width="80px" runat="server"></asp:textbox>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:BoundField DataField="Job" HeaderText="Job" />

    </Columns>
    </asp:GridView>

    <input type="hidden" runat="server" id="hidMaHDDV" />

    </div>
    <!-- End List -->


    <!-- Begin Addnew -->
    <div role="tabpanel" class="tab-pane" id="Addnewtab">

    <div>

    <label for="thangnam">Month &nbsp;&nbsp;&nbsp;
    <asp:TextBox id="txtThangNam_addnew" width="128px" Height ="30px" runat="server" MaxLength="7" ></asp:TextBox>

    <ajaxToolkit:CalendarExtender id="calendar1" ClientIDMode="Static" runat="server" TargetControlID="txtThangNam_addnew" Format="MM/yyyy"
    DefaultView="Months" OnClientShown="onCalendarShown"
    OnClientHidden="onCalendarHidden" PopupButtonID="imgStart" />
    </label>

    <label for="trangthai">status&nbsp;
    <asp:DropDownList id="DropDownList_Status" OnSelectedIndexChanged="DropDownList_Status_selectedIndexChanged" AutoPostBack="true" runat="server" >
    <asp:ListItem Text="All" Value="All"></asp:ListItem>
    <asp:ListItem Text="status1" Value="1"></asp:ListItem>
    <asp:ListItem Text="status2" Value="2"></asp:ListItem>
    </asp:DropDownList>
    </label>

    <label for="lblbenefit" id="lblbenefit" runat="server">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Benefit (4)&nbsp;
    <asp:DropDownList id="DropDownList_Benefit" runat="server" >
    <asp:ListItem Text="2" Value="2"></asp:ListItem>
    <asp:ListItem Text="3" Value="3"></asp:ListItem>
    <asp:ListItem Text="4" Value="4"></asp:ListItem>
    </asp:DropDownList>
    </label>

    </div>


    <asp:Gridview id="GridView2" CssClass="dt-responsive" class="display" Width="100%" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#BED7F3" HeaderStyle-Height="30px" HeaderStyle-BorderStyle="None" HeaderStyle-ForeColor="#144383" Font-Names="Arial" HeaderStyle-Font-Size="13px">

    <Columns>

    <asp:TemplateField HeaderText="Id" HeaderStyle-Width ="20px">
    <ItemTemplate>
    <asp:Label ID="txtId" Width="20px" Text='<%# Eval("MyId") %>' runat="server"></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Customer Name" >
    <ItemTemplate>
    <asp:textbox ID="txtName" Text='<%# Eval("MyName") %>' Width="150px" runat="server"></asp:textbox>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="CountryCode" Visible="false">
    <ItemTemplate>
    <asp:Label ID="txtCountryCode" Text='<%# Eval("CountryCode") %>' runat="server" Visible="false"></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>


    <asp:TemplateField HeaderText="Country" >
    <ItemTemplate>
    <asp:textbox ID="txtCountry" Text='<%# Eval("MyCountry") %>' Width="100px" runat="server" ></asp:textbox>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Salary1" >
    <ItemTemplate>
    <asp:textbox ID="txtSalary1" onkeyup="isNumberKey(this);" Text='<%# Eval("MySalary1") %>' Width="80px" runat="server"></asp:textbox>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Salary2" >
    <ItemTemplate>
    <asp:textbox ID="txtSalary2" onkeyup="isNumberKey(this);" Text='<%# Eval("MySalary2") %>' Width="80px" runat="server"></asp:textbox>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Salary=(1+2)" >
    <ItemTemplate>
    <asp:textbox ID="txtSalary12" onkeyup="isNumberKey(this);" Text='<%# Eval("MySalary12") %>' Width="80px" runat="server"></asp:textbox>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Divide(3)" >
    <ItemTemplate>
    <asp:DropDownList ID="txtDivide" runat="server" AppendDataBoundItems="true">
    </asp:DropDownList>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Benefit(4)" >
    <ItemTemplate>
    <asp:textbox ID="txtBenefit" ReadOnly="true" Text='<%# Eval("MyBenefit") %>' Width="80px" runat="server"></asp:textbox>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Received=(1+2)/3+4" >
    <ItemTemplate>
    <asp:textbox ID="txtReceived" ReadOnly="true" Text='<%# Eval("MyReceived") %>' Width="80px" runat="server"></asp:textbox>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Remove" HeaderStyle-Width="50px" >
    <ItemTemplate>
    <asp:Button ID="bttRemoveRow" Width="100px" Text="Remove row" runat="server" onclick="bttRemoveRow_Click" Class="btn-primary"></asp:Button>
    </ItemTemplate>
    </asp:TemplateField>

    </Columns>
    </asp:Gridview>

    <div align="right" >
    <asp:Button ID="ButtonAdd" runat="server" Text="Add row" onclick="ButtonAdd_Click" Class="btn-primary" />
    </div>
    <br />
    <div align="right" >
    <label for="tungay" id="lblTotalReceived" runat="server">Total Received:
    <asp:TextBox ID="txtTotalReceived" ReadOnly="true" runat="server" />
    </label>
    </div>


    <div align="Left" >
    <asp:Button ID="ButtonSaveAll" runat="server" Text="Save all row" onclick="ButtonSaveAll_Click" Class="btn-primary" />
    </div>


    </div>
    <!-- End Addnew -->

    <!-- Begin Edit -->
    <div role="tabpanel" class="tab-pane" id="Edittab">
    Edit
    </div>
    <!-- End Edit -->


    <!-- Begin View -->
    <div role="tabpanel" class="tab-pane" id="Viewtab">
    View
    </div>
    <!-- End View -->

    </div>
    </div>
    </div>

    <asp:HiddenField ID="HiddenTab" runat="server" />

    </ContentTemplate>
    </asp:UpdatePanel>

    <!-- Panel End-->

    <script type="text/javascript">

    function isNumberKey(i) {
    if (i.value.length > 0) {
    i.value = i.value.replace(/[^\d]+/g, ''); // Only number
    i.value = i.value.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); // group for currency
    }

    }

    function RememberValue() {
    var table = $('#<%=GridView2.ClientID%>').DataTable({
    "paging": false,
    "ordering": true,
    "searching": false,
    "destroy": true,
    'columnDefs': [
    {
    //"defaultContent": "-",
    'targets': [1, 2, 3, 4],
    'render': function (data, type, row, meta) {
    if (type === 'display') {
    var api = new $.fn.dataTable.Api(meta.settings);

    var $el = $('input, select, textarea', api.cell({ row: meta.row, column: meta.col }).node());

    var $html = $(data).wrap('<div/>').parent();

    if ($el.prop('tagName') === 'INPUT') {
    $('input', $html).attr('value', $el.val());
    if ($el.prop('checked')) {
    $('input', $html).attr('checked', 'checked');
    }
    } else if ($el.prop('tagName') === 'TEXTAREA') {
    $('textarea', $html).html($el.val());

    } else if ($el.prop('tagName') === 'SELECT') {
    $('option:selected', $html).removeAttr('selected');
    $('option', $html).filter(function () {
    return ($(this).attr('value') === $el.val());
    }).attr('selected', 'selected');
    }

    data = $html.html();
    }

    return data;
    }
    }

    ],
    'responsive': true
    });

    // Update original input/select on change in child row
    $('#<%=GridView2.ClientID%> tbody').on('keyup change', '.child input, .child select, .child textarea', function (e) {

    var $el = $(this);
    var rowIdx = $el.closest('ul').data('dtr-index');
    var colIdx = $el.closest('li').data('dtr-index');
    var cell = table.cell({ row: rowIdx, column: colIdx }).node();
    $('input, select, textarea', cell).val($el.val());
    if ($el.is(':checked')) {
    $('input', cell).prop('checked', true);
    } else {
    $('input', cell).removeProp('checked');
    }
    });
    };



    function SetTabs() {
    var tabName = $("[id*=HiddenTab]").val() != "" ? $("[id*=HiddenTab]").val() : "Listtab";
    $('#dvTab a[href="#' + tabName + '"]').tab('show');
    $('#dvTab a').on('shown.bs.tab', function (e) {
    $("[id*=HiddenTab]").val($(this).attr("href").replace("#", ""));
    $($.fn.dataTable.tables(true)).DataTable()
    .columns.adjust()
    .responsive.recalc();
    });

    };

    </script>

    <script type="text/javascript">

    function pageLoad() {
    SetTabs();
    gridView1DataTable();
    RememberValue();

    }

    function gridView1DataTable() {
    var table = $('#<%=GridView1.ClientID%>').DataTable({ "destroy": true, "paging": false, "ordering": false, "searching": false, 'responsive': true, "AutoWidth": false });

    }
    </script>

    <script type="text/javascript">
    function onCalendarHidden() { // Call on Addnew
    var cal = $find("calendar1");

    if (cal._monthsBody) {
    for (var i = 0; i < cal._monthsBody.rows.length; i++) {
    var row = cal._monthsBody.rows[i];
    for (var j = 0; j < row.cells.length; j++) {
    Sys.UI.DomEvent.removeHandler(row.cells[j].firstChild, "click", call);
    }
    }
    }
    }

    function onCalendarShown() {

    var cal = $find("calendar1");

    cal._switchMode("months", true);

    if (cal._monthsBody) {
    for (var i = 0; i < cal._monthsBody.rows.length; i++) {
    var row = cal._monthsBody.rows[i];
    for (var j = 0; j < row.cells.length; j++) {
    Sys.UI.DomEvent.addHandler(row.cells[j].firstChild, "click", call);
    }
    }
    }
    }

    function call(eventElement) {
    var target = eventElement.target;
    switch (target.mode) {
    case "month":
    var cal = $find("calendar1");
    cal._visibleDate = target.date;
    cal.set_selectedDate(target.date);
    //cal._switchMonth(target.date);
    cal._blur.post(true);
    cal.raiseDateSelectionChanged();
    break;
    }
    }
    </script>

    </asp:Content>

    
    
    CS.aspx.cs

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace Quanlynhachothue
    {
    public partial class CS : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    if (!this.IsPostBack)
    {
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country"), new DataColumn("Salary"), new DataColumn("Job") });
    dt.Rows.Add(1, "John Hammond", "United States", 70000, "IT");
    dt.Rows.Add(2, "Mudassar Khan", "India", 40000, "Bank");
    dt.Rows.Add(3, "Suzanne Mathews", "France", 30000, "Sport");
    dt.Rows.Add(4, "Robert Schidner", "Russia", 50000, "Finace");

    GridView1.DataSource = dt;
    GridView1.DataBind();
    GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;

    ButtonAdd.Visible = false;
    ButtonSaveAll.Visible = false;

    lblbenefit.Visible = false;
    DropDownList_Benefit.Visible = false;

    lblTotalReceived.Visible = false;
    txtTotalReceived.Visible = false;
    }
    else
    GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;

    if (ViewState["CurrentTable"] != null)
    GridView2.HeaderRow.TableSection = TableRowSection.TableHeader;
    }

    protected void Create_GridView2()
    {
    DataTable dt1 = new DataTable();
    DataRow dr = null;

    dt1.Columns.AddRange(new DataColumn[10]
    {
    new DataColumn("MyId"), //0
    new DataColumn("MyName"), //1
    new DataColumn("CountryCode"), //2
    new DataColumn("MyCountry"), //3
    new DataColumn("MySalary1"), //4
    new DataColumn("MySalary2"), //5
    new DataColumn("MySalary12"), //6 MySalary12=MySalary1 + MySalary2
    new DataColumn("MyDivide"), //7
    new DataColumn("MyBenefit"), //8
    new DataColumn("MyReceived") //9 MyReceived= MySalary12 / MyDivide + Benefit
    });

    dr = dt1.NewRow();
    dr["MyId"] = 1;
    dr["MyName"] = "Robert Schidner";
    dr["CountryCode"] = 10;
    dr["MyCountry"] = "France";
    dr["MySalary1"] = String.Format("{0:#,##0}", double.Parse("1050"));
    dr["MySalary2"] = String.Format("{0:#,##0}", double.Parse("2050"));
    dt1.Rows.Add(dr);

    dr = dt1.NewRow();
    dr["MyId"] = 2;
    dr["MyName"] = "Mudassar Khan";
    dr["CountryCode"] = 15;
    dr["MyCountry"] = "India";
    dr["MySalary1"] = String.Format("{0:#,##0}", double.Parse("2150"));
    dr["MySalary2"] = String.Format("{0:#,##0}", double.Parse("1250"));
    dt1.Rows.Add(dr);

    dr = dt1.NewRow();
    dr["MyId"] = 3;
    dr["MyName"] = "Suzanne Mathews";
    dr["CountryCode"] = 20;
    dr["MyCountry"] = "United States";
    dr["MySalary1"] = String.Format("{0:#,##0}", double.Parse("1820"));
    dr["MySalary2"] = String.Format("{0:#,##0}", double.Parse("1280"));
    dt1.Rows.Add(dr);


    //Store the DataTable in ViewState for future reference
    ViewState["CurrentTable"] = dt1;

    //Bind the Gridview
    GridView2.DataSource = dt1;
    GridView2.DataBind();
    GridView2.HeaderRow.TableSection = TableRowSection.TableHeader;

    DropDownList ddl2 = null;

    DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];

    //After binding the gridview, we can then extract and fill the DropDownList with Data
    for (int j = 0; j < dtCurrentTable.Rows.Count; j++)
    {
    ddl2 = (DropDownList)GridView2.Rows[j].Cells[7].FindControl("txtDivide");
    DropDownList_Divide(ddl2);
    }


    }

    /*
    public static void DropDownList_Country(DropDownList ddl)
    {
    System.Collections.ArrayList arr = new System.Collections.ArrayList();

    arr.Add(new ListItem("United States", "1"));
    arr.Add(new ListItem("India", "2"));
    arr.Add(new ListItem("France", "3"));
    arr.Add(new ListItem("Russia", "4"));

    foreach (ListItem item in arr)
    {
    ddl.Items.Add(item);
    }
    }
    */

    public static void DropDownList_Divide(DropDownList ddl)
    {
    System.Collections.ArrayList arr = new System.Collections.ArrayList();

    arr.Add(new ListItem("None", "None"));
    arr.Add(new ListItem("2", "2"));
    arr.Add(new ListItem("3", "3"));
    arr.Add(new ListItem("4", "4"));
    arr.Add(new ListItem("5", "5"));
    arr.Add(new ListItem("6", "6"));

    foreach (ListItem item in arr)
    {
    ddl.Items.Add(item);
    }
    }

    private void AddNewRowToGrid()
    {

    if (ViewState["CurrentTable"] != null)
    {

    DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
    DataRow drCurrentRow = null;

    if (dtCurrentTable.Rows.Count > 0)
    {
    drCurrentRow = dtCurrentTable.NewRow();
    drCurrentRow["MyId"] = dtCurrentTable.Rows.Count + 1;

    drCurrentRow["MySalary1"] = String.Format("{0:#,##0}", double.Parse("1550"));
    drCurrentRow["MySalary2"] = String.Format("{0:#,##0}", double.Parse("2550"));

    //add new row to DataTable
    dtCurrentTable.Rows.Add(drCurrentRow);

    for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++)
    {

    //extract the TextBox values

    TextBox txt_Name = (TextBox)GridView2.Rows[i].Cells[1].FindControl("txtName");
    Label txt_CountryCode = (Label)GridView2.Rows[i].Cells[2].FindControl("txtCountryCode");
    TextBox txt_MyCountry = (TextBox)GridView2.Rows[i].Cells[3].FindControl("txtCountry");
    TextBox txt_Salary1 = (TextBox)GridView2.Rows[i].Cells[4].FindControl("txtSalary1");
    TextBox txt_Salary2 = (TextBox)GridView2.Rows[i].Cells[5].FindControl("txtSalary2");
    TextBox txt_Salary12 = (TextBox)GridView2.Rows[i].Cells[6].FindControl("txtSalary12");
    TextBox txt_Benefit = (TextBox)GridView2.Rows[i].Cells[8].FindControl("txtBenefit");
    TextBox txt_Received = (TextBox)GridView2.Rows[i].Cells[9].FindControl("txtReceived");


    dtCurrentTable.Rows[i]["MyName"] = txt_Name.Text;
    dtCurrentTable.Rows[i]["CountryCode"] = txt_CountryCode.Text;
    dtCurrentTable.Rows[i]["MyCountry"] = txt_MyCountry.Text;
    dtCurrentTable.Rows[i]["MySalary1"] = txt_Salary1.Text;
    dtCurrentTable.Rows[i]["MySalary2"] = txt_Salary2.Text;
    dtCurrentTable.Rows[i]["MySalary12"] = txt_Salary12.Text;
    dtCurrentTable.Rows[i]["MyBenefit"] = txt_Benefit.Text;
    dtCurrentTable.Rows[i]["MyReceived"] = txt_Received.Text;

    //extract the DropDownList Selected Items
    DropDownList ddl2 = (DropDownList)GridView2.Rows[i].Cells[7].FindControl("txtDivide");

    // Update the DataRow with the DDL Selected Items
    dtCurrentTable.Rows[i]["MyDivide"] = ddl2.SelectedItem.Text;
    }

    //Store the current data to ViewState for future reference
    ViewState["CurrentTable"] = dtCurrentTable;


    //Rebind the Grid with the current data to reflect changes
    GridView2.DataSource = dtCurrentTable;
    GridView2.DataBind();
    GridView2.HeaderRow.TableSection = TableRowSection.TableHeader;
    }
    }
    else
    {
    Response.Write("ViewState is null");

    }
    //Set Previous Data on Postbacks
    SetPreviousData();
    }


    protected void DropDownList_Status_selectedIndexChanged(object sender, EventArgs e)
    {
    if (DropDownList_Status.SelectedItem.Text != "All")
    {
    Create_GridView2();
    ButtonAdd.Visible = true;
    ButtonSaveAll.Visible = true;

    lblbenefit.Visible = true;
    DropDownList_Benefit.Visible = true;

    lblTotalReceived.Visible = true;
    txtTotalReceived.Visible = true;
    }
    else
    {
    GridView2.DataSource = null;
    GridView2.DataBind();

    ButtonAdd.Visible = false;
    ButtonSaveAll.Visible = false;

    lblbenefit.Visible = false;
    DropDownList_Benefit.Visible = false;

    lblTotalReceived.Visible = false;
    txtTotalReceived.Visible = false;
    }

    }

    protected void ButtonSaveAll_Click(object sender, EventArgs e)
    {

    }


    protected void bttRemoveRow_Click(object sender, EventArgs e)
    {
    UpdateCurrentDataTable(GridView2);
    Button btt = (Button)sender;
    GridViewRow gvRow = (GridViewRow)btt.NamingContainer;
    int rowID = gvRow.RowIndex;
    if (ViewState["CurrentTable"] != null)
    {

    DataTable dt = (DataTable)ViewState["CurrentTable"];
    if (dt.Rows.Count > 1)
    {
    if (gvRow.RowIndex <= dt.Rows.Count - 1)
    {
    //Remove the Selected Row data and reset row number
    dt.Rows.Remove(dt.Rows[rowID]);
    ResetRowID(dt);
    }
    }

    //Store the current data in ViewState for future reference
    ViewState["CurrentTable"] = dt;

    //Re bind the GridView for the updated data except dropdown lists
    GridView2.DataSource = dt;
    GridView2.DataBind();
    GridView2.HeaderRow.TableSection = TableRowSection.TableHeader;

    //After binding the gridview, we can then extract and fill the DropDownList with Data
    for (int j = 0; j < dt.Rows.Count; j++)
    {
    DropDownList ddl2 = (DropDownList)GridView2.Rows[j].FindControl("txtDivide");

    DropDownList_Divide(ddl2);

    ddl2.ClearSelection();
    ddl2.Items.FindByText(dt.Rows[j]["MyDivide"].ToString()).Selected = true;

    }
    }

    }

    private void UpdateCurrentDataTable(GridView gv)
    {
    int rowIndex = 0;
    if (ViewState["CurrentTable"] != null)
    {
    DataTable dt = (DataTable)ViewState["CurrentTable"];
    foreach (GridViewRow row in gv.Rows)
    {
    Label lbl_Id = (Label)row.FindControl("txtId");
    TextBox tb_Name = (TextBox)row.FindControl("txtName");
    Label lbl_CountryCode = (Label)row.FindControl("txtCountryCode");
    TextBox lbl_Country = (TextBox)row.FindControl("txtCountry");
    TextBox tb_Salary1 = (TextBox)row.FindControl("txtSalary1");
    TextBox tb_Salary2 = (TextBox)row.FindControl("txtSalary2");
    TextBox tb_Salary12 = (TextBox)row.FindControl("txtSalary12");
    TextBox tb_Benefit = (TextBox)row.FindControl("txtBenefit");
    TextBox tb_Received = (TextBox)row.FindControl("txtReceived");

    DropDownList dpl_Divide = (DropDownList)row.FindControl("txtDivide");

    int id = Convert.ToInt32(lbl_Id.Text);
    string name = tb_Name.Text;
    string countryCode = lbl_CountryCode.Text;
    string country = lbl_Country.Text;
    string salary1 = tb_Salary1.Text;
    string salary2 = tb_Salary2.Text;
    string salary12 = tb_Salary12.Text;
    string Benefit = tb_Benefit.Text;
    string Received = tb_Received.Text;


    string Divide = dpl_Divide.SelectedItem.Text;

    dt.Rows[rowIndex]["MyId"] = id;
    dt.Rows[rowIndex]["MyName"] = name;
    dt.Rows[rowIndex]["CountryCode"] = countryCode;
    dt.Rows[rowIndex]["MyCountry"] = country;
    dt.Rows[rowIndex]["MySalary1"] = salary1;
    dt.Rows[rowIndex]["MySalary2"] = salary2;
    dt.Rows[rowIndex]["MySalary12"] = salary12;
    dt.Rows[rowIndex]["MyBenefit"] = Benefit;
    dt.Rows[rowIndex]["MyReceived"] = Received;

    dt.Rows[rowIndex]["MyDivide"] = Divide;
    rowIndex++;
    }
    ViewState["CurrentTable"] = dt;
    }
    }

    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
    AddNewRowToGrid();
    }

    private void ResetRowID(DataTable dt)
    {
    int rowNumber = 1;
    if (dt.Rows.Count > 0)
    {
    foreach (DataRow row in dt.Rows)
    {
    row[0] = rowNumber;
    rowNumber++;
    }
    }
    }
    private void SetPreviousData()
    {

    int rowIndex = 0;
    if (ViewState["CurrentTable"] != null)
    {

    DataTable dt = (DataTable)ViewState["CurrentTable"];
    if (dt.Rows.Count > 0)
    {

    for (int i = 0; i < dt.Rows.Count; i++)
    {

    Label txt_Id = (Label)GridView2.Rows[i].Cells[0].FindControl("txtId");
    TextBox txt_Name = (TextBox)GridView2.Rows[i].Cells[1].FindControl("txtName");
    Label txt_CountryCode = (Label)GridView2.Rows[i].Cells[2].FindControl("txtCountryCode");
    TextBox txt_Country = (TextBox)GridView2.Rows[i].Cells[3].FindControl("txtCountry");

    TextBox txt_Salary1 = (TextBox)GridView2.Rows[i].Cells[4].FindControl("txtSalary1");
    TextBox txt_Salary2 = (TextBox)GridView2.Rows[i].Cells[5].FindControl("txtSalary2");
    TextBox txt_Salary12 = (TextBox)GridView2.Rows[i].Cells[6].FindControl("txtSalary12");
    DropDownList ddl2 = (DropDownList)GridView2.Rows[rowIndex].Cells[7].FindControl("txtDivide");
    TextBox txt_Benefit = (TextBox)GridView2.Rows[i].Cells[8].FindControl("txtBenefit");
    TextBox txt_Received = (TextBox)GridView2.Rows[i].Cells[9].FindControl("txtReceived");


    //Fill the DropDownList with Data
    DropDownList_Divide(ddl2);

    if (i < dt.Rows.Count - 1)
    {
    txt_Id.Text = dt.Rows[i]["MyId"].ToString();
    txt_Name.Text = dt.Rows[i]["MyName"].ToString();
    txt_CountryCode.Text = dt.Rows[i]["CountryCode"].ToString();
    txt_Country.Text = dt.Rows[i]["MyCountry"].ToString();

    txt_Salary1.Text = dt.Rows[i]["MySalary1"].ToString();
    txt_Salary2.Text = dt.Rows[i]["MySalary2"].ToString();
    txt_Salary12.Text = dt.Rows[i]["MySalary12"].ToString();
    txt_Benefit.Text = dt.Rows[i]["MyBenefit"].ToString();
    txt_Received.Text = dt.Rows[i]["MyReceived"].ToString();

    //Set the Previous Selected Items on Each DropDownList on Postbacks
    ddl2.ClearSelection();
    ddl2.Items.FindByText(dt.Rows[i]["MyDivide"].ToString()).Selected = true;
    }

    rowIndex++;
    }
    }
    }
    }
    }
    }

    
    

    Please help me soon, thank advance!

    Wednesday, April 15, 2020 5:47 PM

Answers

  • User-1330468790 posted

    Hi test0101,

     

    test0101

    I update your code but not effect, then I review and detect that you added to .aspx, but not mark YESLOW then I can't see.

    I posted previous example to show you that how you could handle the instant update for the textboxes/label.

    What you need to focus on is the Javascript functions I made.

     

    test0101

    think, because I use master page, in that I have <form> tag.

    And ScriptManager already in .aspx as:

    <!-- Begin List -->
    <div role="tabpanel" class="tab-pane active" id="Listtab">
    <div>
    <asp:ScriptManager id="toolScriptManageer1" runat="server" EnablePartialRendering="false"> </asp:ScriptManager>

    are you building code with my master page?

    No, I recreate a complete new webform page with the necessary code for the "GridView2" control.

    If you find that it is difficult to integrate the javascript code, below code might be helpful. 

    I insert some "console.log()" in the code which would be helpful for you understanding the code easier (Press F12 in browser).

     

    .aspx Page: Scroll down to pageload() function.

    (No any change on your code except new added javascript functions)

    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <div class="tab-content" style="width: auto; border: none; font-family: Arial; font-size: larger; color: #1443AB; font-weight: bold; text-align: center; padding: 1px; margin: 1px">
                    GRIDVIEW
                </div>
                <div class="panel panel-default" style="width: auto; padding: 6px; margin: 6px">
    
                    <div id="dvTab">
    
                        <ul class="nav nav-tabs" role="tablist" style="font-weight: bold">
                            <li runat="server" id="idListtab" class="active"><a href="#Listtab" style="outline: none" aria-controls="Listtab" role="tab" data-toggle="tab">LIST</a></li>
                            <li runat="server" id="idAddnewtab"><a href="#Addnewtab" style="outline: none" aria-controls="Addnewtab" role="tab" data-toggle="tab">ADD NEW</a></li>
                            <li runat="server" id="idEdittab"><a href="#Edittab" style="outline: none" aria-controls="Edittab" role="tab" data-toggle="tab">EDIT</a></li>
                            <li runat="server" id="idViewtab"><a href="#Viewtab" style="outline: none" aria-controls="Viewtab" role="tab" data-toggle="tab">VIEW</a></li>
    
                        </ul>
    
                        <div class="tab-content" style="padding-top: 5px">
    
                            <!-- Begin List -->
                            <div role="tabpanel" class="tab-pane active" id="Listtab">
    
                                <div>
    
                                    <asp:ScriptManager ID="toolScriptManageer1" runat="server" EnablePartialRendering="false">
                                    </asp:ScriptManager>
    
                                    <label for="tungay">
                                        From &nbsp;&nbsp;&nbsp;
                                        <asp:TextBox ID="txtTungay" Width="128px" Height="30px" runat="server" MaxLength="10" AutoPostBack="true"></asp:TextBox>
                                        <ajaxtoolkit:calendarextender id="Calendarfromdate" popupbuttonid="imgPopup" runat="server" targetcontrolid="txtTungay" format="dd/MM/yyyy" />
                                    </label>
    
    
                                    <label for="denngay">
                                        To &nbsp;
    
                                        <asp:TextBox ID="txtDenngay" Width="128px" Height="30px" AutoPostBack="true" runat="server" MaxLength="10"></asp:TextBox>
                                        <ajaxtoolkit:calendarextender id="Calendartodate" popupbuttonid="imgPopup" runat="server" targetcontrolid="txtDenngay" format="dd/MM/yyyy" />
    
                                    </label>
    
                                    <label for="trangthai">
                                        Status&nbsp;
                                        <asp:DropDownList ID="txtTrangthai" Width="128px" Height="30px" AutoPostBack="true" runat="server">
                                            <asp:ListItem Text="All" Value="All"></asp:ListItem>
                                            <asp:ListItem Text="status1" Value="1"></asp:ListItem>
                                            <asp:ListItem Text="status2" Value="2"></asp:ListItem>
                                        </asp:DropDownList>
                                    </label>
    
                                </div>
                                <br />
    
                                <asp:GridView ID="GridView1" CssClass="dt-responsive" class="display" Width="100%" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#BED7F3" HeaderStyle-Height="30px" HeaderStyle-BorderStyle="None" HeaderStyle-ForeColor="#144383" Font-Names="Arial" HeaderStyle-Font-Size="13px">
    
                                    <Columns>
                                        <asp:BoundField DataField="Id" HeaderText="Customer Id" />
                                        <asp:BoundField DataField="Name" HeaderText="Customer Name" />
                                        <asp:BoundField DataField="Country" HeaderText="Country" />
    
                                        <asp:TemplateField HeaderText="Salary">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtSalary" Text='<%# Eval("Salary") %>' Width="80px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:BoundField DataField="Job" HeaderText="Job" />
    
                                    </Columns>
                                </asp:GridView>
    
                                <input type="hidden" runat="server" id="hidMaHDDV" />
    
                            </div>
                            <!-- End List -->
    
    
                            <!-- Begin Addnew -->
                            <div role="tabpanel" class="tab-pane" id="Addnewtab">
    
                                <div>
    
                                    <label for="thangnam">
                                        Month &nbsp;&nbsp;&nbsp;
                                        <asp:TextBox ID="txtThangNam_addnew" Width="128px" Height="30px" runat="server" MaxLength="7"></asp:TextBox>
    
                                        <ajaxtoolkit:calendarextender id="calendar1" clientidmode="Static" runat="server" targetcontrolid="txtThangNam_addnew" format="MM/yyyy"
                                            defaultview="Months" onclientshown="onCalendarShown"
                                            onclienthidden="onCalendarHidden" popupbuttonid="imgStart" />
                                    </label>
    
                                    <label for="trangthai">
                                        status&nbsp;
                                        <asp:DropDownList ID="DropDownList_Status" OnSelectedIndexChanged="DropDownList_Status_selectedIndexChanged" AutoPostBack="true" runat="server">
                                            <asp:ListItem Text="All" Value="All"></asp:ListItem>
                                            <asp:ListItem Text="status1" Value="1"></asp:ListItem>
                                            <asp:ListItem Text="status2" Value="2"></asp:ListItem>
                                        </asp:DropDownList>
                                    </label>
    
                                    <label for="lblbenefit" id="lblbenefit" runat="server">
                                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Benefit (4)&nbsp;
                                        <asp:DropDownList ID="DropDownList_Benefit" runat="server">
                                            <asp:ListItem Text="2" Value="2"></asp:ListItem>
                                            <asp:ListItem Text="3" Value="3"></asp:ListItem>
                                            <asp:ListItem Text="4" Value="4"></asp:ListItem>
                                        </asp:DropDownList>
                                    </label>
    
                                </div>
    
    
                                <asp:GridView ID="GridView2" CssClass="dt-responsive" class="display" Width="100%" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#BED7F3" HeaderStyle-Height="30px" HeaderStyle-BorderStyle="None" HeaderStyle-ForeColor="#144383" Font-Names="Arial" HeaderStyle-Font-Size="13px">
    
                                    <Columns>
    
                                        <asp:TemplateField HeaderText="Id" HeaderStyle-Width="20px">
                                            <ItemTemplate>
                                                <asp:Label ID="txtId" Width="20px" Text='<%# Eval("MyId") %>' runat="server"></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Customer Name">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtName" Text='<%# Eval("MyName") %>' Width="150px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="CountryCode" Visible="false">
                                            <ItemTemplate>
                                                <asp:Label ID="txtCountryCode" Text='<%# Eval("CountryCode") %>' runat="server" Visible="false"></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
    
                                        <asp:TemplateField HeaderText="Country">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtCountry" Text='<%# Eval("MyCountry") %>' Width="100px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Salary1">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtSalary1" onkeyup="isNumberKey(this);" Text='<%# Eval("MySalary1") %>' Width="80px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Salary2">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtSalary2" onkeyup="isNumberKey(this);" Text='<%# Eval("MySalary2") %>' Width="80px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Salary=(1+2)">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtSalary12" onkeyup="isNumberKey(this);" Text='<%# Eval("MySalary12") %>' Width="80px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Divide(3)">
                                            <ItemTemplate>
                                                <asp:DropDownList ID="txtDivide" runat="server" AppendDataBoundItems="true">
                                                </asp:DropDownList>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Benefit(4)">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtBenefit" ReadOnly="true" Text='<%# Eval("MyBenefit") %>' Width="80px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Received=(1+2)/3+4">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtReceived" ReadOnly="true" Text='<%# Eval("MyReceived") %>' Width="80px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Remove" HeaderStyle-Width="50px">
                                            <ItemTemplate>
                                                <asp:Button ID="bttRemoveRow" Width="100px" Text="Remove row" runat="server" OnClick="bttRemoveRow_Click" Class="btn-primary"></asp:Button>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                    </Columns>
                                </asp:GridView>
    
                                <div align="right">
                                    <asp:Button ID="ButtonAdd" runat="server" Text="Add row" OnClick="ButtonAdd_Click" Class="btn-primary" />
                                </div>
                                <br />
                                <div align="right">
                                    <label for="tungay" id="lblTotalReceived" runat="server">
                                        Total Received:
                                        <asp:TextBox ID="txtTotalReceived"  runat="server" />
                                    </label>
                                </div>
    
    
                                <div align="Left">
                                    <asp:Button ID="ButtonSaveAll" runat="server" Text="Save all row" OnClick="ButtonSaveAll_Click" Class="btn-primary" />
                                </div>
    
    
                            </div>
                            <!-- End Addnew -->
    
                            <!-- Begin Edit -->
                            <div role="tabpanel" class="tab-pane" id="Edittab">
                                Edit
                            </div>
                            <!-- End Edit -->
    
    
                            <!-- Begin View -->
                            <div role="tabpanel" class="tab-pane" id="Viewtab">
                                View
                            </div>
                            <!-- End View -->
    
                        </div>
                    </div>
                </div>
    
                <asp:HiddenField ID="HiddenTab" runat="server" />
    
            </ContentTemplate>
        </asp:UpdatePanel>
    
        <!-- Panel End-->
    
        <script type="text/javascript">
    
            function isNumberKey(i) {
                if (i.value.length > 0) {
                    i.value = i.value.replace(/[^\d]+/g, ''); // Only number
                    i.value = i.value.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); // group for currency
                }
    
            }
    
            function RememberValue() {
                var table = $('#<%=GridView2.ClientID%>').DataTable({
            "paging": false,
            "ordering": true,
            "searching": false,
            "destroy": true,
            'columnDefs': [
                {
                    //"defaultContent": "-",
                    'targets': [1, 2, 3, 4],
                    'render': function (data, type, row, meta) {
                        if (type === 'display') {
                            var api = new $.fn.dataTable.Api(meta.settings);
    
                            var $el = $('input, select, textarea', api.cell({ row: meta.row, column: meta.col }).node());
    
                            var $html = $(data).wrap('<div/>').parent();
    
                            if ($el.prop('tagName') === 'INPUT') {
                                $('input', $html).attr('value', $el.val());
                                if ($el.prop('checked')) {
                                    $('input', $html).attr('checked', 'checked');
                                }
                            } else if ($el.prop('tagName') === 'TEXTAREA') {
                                $('textarea', $html).html($el.val());
    
                            } else if ($el.prop('tagName') === 'SELECT') {
                                $('option:selected', $html).removeAttr('selected');
                                $('option', $html).filter(function () {
                                    return ($(this).attr('value') === $el.val());
                                }).attr('selected', 'selected');
                            }
    
                            data = $html.html();
                        }
    
                        return data;
                    }
                }
    
            ],
            'responsive': true
        });
    
        // Update original input/select on change in child row
        $('#<%=GridView2.ClientID%> tbody').on('keyup change', '.child input, .child select, .child textarea', function (e) {
    
                    var $el = $(this);
                    var rowIdx = $el.closest('ul').data('dtr-index');
                    var colIdx = $el.closest('li').data('dtr-index');
                    var cell = table.cell({ row: rowIdx, column: colIdx }).node();
                    $('input, select, textarea', cell).val($el.val());
                    if ($el.is(':checked')) {
                        $('input', cell).prop('checked', true);
                    } else {
                        $('input', cell).removeProp('checked');
                    }
                });
            };
    
    
    
            function SetTabs() {
                var tabName = $("[id*=HiddenTab]").val() != "" ? $("[id*=HiddenTab]").val() : "Listtab";
                $('#dvTab a[href="#' + tabName + '"]').tab('show');
                $('#dvTab a').on('shown.bs.tab', function (e) {
                    $("[id*=HiddenTab]").val($(this).attr("href").replace("#", ""));
                    $($.fn.dataTable.tables(true)).DataTable()
                        .columns.adjust()
                        .responsive.recalc();
                });
    
            };
    
        </script>
    
        <script type="text/javascript">
    
            function pageLoad() {
                SetTabs();
                gridView1DataTable();
                RememberValue();
                //Below are new Added functions for update value automatically
                bindEventBenefitDDL();
                updateTotalReceived();
                bindEventReceived();
    
            }
    
    
            function bindEventBenefitDDL() {
                //Update all txtBenefit field with the value of this drop down list
                $('#<%=DropDownList_Benefit.ClientID%>').on('change', function () {
                     var value = $(this).val();
                    var txtBenefitGroup = $('#<%=GridView2.ClientID%> input[id*=txtBenefit]');
                        var count = txtBenefitGroup.length - 1;
                        //Update each txtBenefit and update the TotalReceived input field after the update completed
                        txtBenefitGroup.each(function (i, element) {
                            $(this).val(value);
                            if (i == count) {
                                updateTotalReceived();
                            };
                        });
    
                    });
    
    
            }
    
            function bindEventReceived() {
                // Bind change event to salary1
                $("td input[id*=txtSalary1").on('change', function () {
                    updateTotalReceived();
                });
    
                // Bind change event to salary2
                $("td input[id*=txtSalary2]").on('change', function () {
                    updateTotalReceived();
                })
    
                // Bind change event to divide
                $("td select[id*=txtDivide]").on('change', function () {
                    updateTotalReceived();
                })
    
            }
    
            function updateTotalReceived() {
                var total = 0;
                //Sum for txtReceiveds in each row
                $('#<%=GridView2.ClientID%> input[id*=txtReceived]').each(function (i, element) {
                        updateRowReceived(this);
                        total += parseInt($(this).val());
                    });
    
                    $('#<%=txtTotalReceived.ClientID%>').val(total);
            }
    
            // You can check the value through the console. If you don't need these consoles anymore, delete it
            function updateRowReceived(element) {
    //Find the current row of the element (txtReceived) var row = $(element).parent().parent(); console.log(row); //Find salary1 in this row var salary1 = row.find("td input[id*=txtSalary1]").val().replace(",",""); console.log('salary1:' + salary1); //Find salary2 in this row var salary2 = row.find("td input[id*=txtSalary2]").val().replace(",",""); console.log('salary2:' + salary2); //Calculate salary1 + salary2 and fil it into salary12 var salaryTotal = parseInt(salary1) + parseInt(salary2); row.find("td input[id*=txtSalary12]").val(salaryTotal); //Get divide value var divide = parseInt(row.find("td select[id*=txtDivide]").val()); console.log('divide:' + divide); //Get benefit value var benefit = parseInt(row.find("td input[id*=txtBenefit]").val()); console.log('benefit:' + benefit); //Fill the txtReceived with the result of calculations $(element).val(salaryTotal / divide + benefit); } function gridView1DataTable() { var table = $('#<%=GridView1.ClientID%>').DataTable({ "destroy": true, "paging": false, "ordering": false, "searching": false, 'responsive': true, "AutoWidth": false }); } </script> <script type="text/javascript"> function onCalendarHidden() { // Call on Addnew var cal = $find("calendar1"); if (cal._monthsBody) { for (var i = 0; i < cal._monthsBody.rows.length; i++) { var row = cal._monthsBody.rows[i]; for (var j = 0; j < row.cells.length; j++) { Sys.UI.DomEvent.removeHandler(row.cells[j].firstChild, "click", call); } } } } function onCalendarShown() { var cal = $find("calendar1"); cal._switchMode("months", true); if (cal._monthsBody) { for (var i = 0; i < cal._monthsBody.rows.length; i++) { var row = cal._monthsBody.rows[i]; for (var j = 0; j < row.cells.length; j++) { Sys.UI.DomEvent.addHandler(row.cells[j].firstChild, "click", call); } } } } function call(eventElement) { var target = eventElement.target; switch (target.mode) { case "month": var cal = $find("calendar1"); cal._visibleDate = target.date; cal.set_selectedDate(target.date); //cal._switchMonth(target.date); cal._blur.post(true); cal.raiseDateSelectionChanged(); break; } } </script> </asp:Content>

    Demo:

     

    Note that I didn't do any format stuff except removing the comma for the currency value of "salary1" and "salary2".

    You could modify the code to achieve whatever format you want.

     

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 17, 2020 5:20 AM
  • User-1330468790 posted

    Hi test0101,

     

    The problem is a bit complicated when the responsive elements were added in the page.

    Sorry that I didn't put the responsive elements under consideration.

      

    You could use below code to refresh the values no matter the page is in responsive size or regular size.

    I didn't change the HTML element. The only thing we need to do is modify the JavaScript code.

    Script:

     

    <script type="text/javascript">
    
            function isNumberKey(i) {
                if (i.value.length > 0) {
                    i.value = i.value.replace(/[^\d]+/g, ''); // Only number
                    i.value = i.value.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); // group for currency
                }
    
            }
    
            function RememberValue() {
                var table = $('#<%=GridView2.ClientID%>').DataTable({
                    "paging": false,
                    "ordering": true,
                    "searching": false,
                    "destroy": true,
                    'columnDefs': [
                        {
                            //"defaultContent": "-",
                            'targets': [1, 2, 3, 4,5,6,7,8],
                            'render': function (data, type, row, meta) {
                                if (type === 'display') {
                                    var api = new $.fn.dataTable.Api(meta.settings);
    
                                    var $el = $('input, select, textarea', api.cell({ row: meta.row, column: meta.col }).node());
    
                                    var $html = $(data).wrap('<div/>').parent();
    
                                    if ($el.prop('tagName') === 'INPUT') {
                                        $('input', $html).attr('value', $el.val());
                                        if ($el.prop('checked')) {
                                            $('input', $html).attr('checked', 'checked');
                                        }
                                    } else if ($el.prop('tagName') === 'TEXTAREA') {
                                        $('textarea', $html).html($el.val());
    
                                    } else if ($el.prop('tagName') === 'SELECT') {
                                        $('option:selected', $html).removeAttr('selected');
                                        $('option', $html).filter(function () {
                                            return ($(this).attr('value') === $el.val());
                                        }).attr('selected', 'selected');
                                    }
    
                                    data = $html.html();
                                }
    
                                return data;
                            }
                        }
    
                    ],
                    'responsive': true
                });
    
               // Update original input/select on change in child row
                $('#<%=GridView2.ClientID%> tbody').on('keyup change', '.child input, .child select, .child textarea', function (e) {
                    
                    var $el = $(this);
                    var rowIdx = $el.closest('ul').data('dtr-index');
                    var colIdx = $el.closest('li').data('dtr-index');
                    var cell = table.cell({ row: rowIdx, column: colIdx }).node();
                    $('input, select, textarea', cell).val($el.val());
    
                    console.log($el.val() + "   XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
                    if ($el.is(':checked')) {
                        $('input', cell).prop('checked', true);
                    } else {
                        $('input', cell).removeProp('checked');
                    }
    
                    updateTotalReceived();
                });
    
    
                table.on('responsive-display', function (e, datatable, row, showHide, update) {
                    
                    updateTotalReceived();
                } );
    
            };
    
    
    
            function SetTabs() {
                var tabName = $("[id*=HiddenTab]").val() != "" ? $("[id*=HiddenTab]").val() : "Listtab";
                $('#dvTab a[href="#' + tabName + '"]').tab('show');
                $('#dvTab a').on('shown.bs.tab', function (e) {
                    $("[id*=HiddenTab]").val($(this).attr("href").replace("#", ""));
                    $($.fn.dataTable.tables(true)).DataTable()
                        .columns.adjust()
                        .responsive.recalc();
                });
    
            };
    
        </script>

    Another Script block.

    <script type="text/javascript">
    
            function pageLoad() {
                SetTabs();
                gridView1DataTable();
                RememberValue();
                //Below are new Added functions for update value automatically
                bindEventBenefitDDL();
    
            }
    
            //Bind DDL to new generate benefit
            function bindEventBenefitDDL() {
                //Update all txtBenefit field with the value of this drop down list
                $('#<%=DropDownList_Benefit.ClientID%>').on('change', function () {
                    var value = $(this).val();
                    var txtBenefitGroup = $('#<%=GridView2.ClientID%> input[id*=txtBenefit]');
                    var count = txtBenefitGroup.length - 1;
                    //Update each txtBenefit and update the TotalReceived input field after the update completed
                    txtBenefitGroup.each(function (i, element) {
                        $(this).val(value);
                        if (i == count) {
                            updateTotalReceived();
                        };
                    });
    
                });
    
    
            }
    
            //Calculate the total received
            function updateTotalReceived() {
                console.log("Trigger updateTotalReceived");
                var table = $('#<%=GridView2.ClientID%>').DataTable();
                var rowCount = table.rows().count();
                var totalRecieved = 0;
                var i;
                for (i = 0; i < rowCount; i++) {
                    //Get salary1
                    var selectorForSalary1 = '#<%=GridView2.ClientID%> input[id*=txtSalary1_' + i + ']';
                    var salary1 = parseInt($(selectorForSalary1).val().replace(",", ""));
    
                    //Get salary2
                    var selectorForSalary2 = '#<%=GridView2.ClientID%> input[id*=txtSalary2_' + i + ']';
                    var salary2 = parseInt($(selectorForSalary2).val().replace(",", ""));
    
                    //Calculate salary12
                    var selectorForSalary12 = '#<%=GridView2.ClientID%> input[id*=txtSalary12_' + i + ']';
                    var salary12 = salary1 + salary2;
                    $(selectorForSalary12).val(salary12);
    
    
                    //Get divide
                    var selectorForDivide = '#<%=GridView2.ClientID%> select[id*=txtDivide_' + i + ']';
                    var divide = parseInt($(selectorForDivide).val());
    
                    //Get benefit
                    var selectorForBenefit = '#<%=GridView2.ClientID%> input[id*=txtBenefit_' + i + ']';
                    var benefit = parseInt($(selectorForBenefit).val());
                   
                    //Get received
                    var selectorForReceived = '#<%=GridView2.ClientID%> input[id*=txtReceived_' + i + ']';
                    var received = (salary12 / divide) + benefit;
                    $(selectorForReceived).val(received);
                    
                    //Increment totalRecieved
                    totalRecieved += received;
    
                }
    
                //Assign value to totalRecieved
                $('input[id*=txtTotalReceived]').val(totalRecieved);
    
            }
    
    function gridView1DataTable() {
                var table = $('#<%=GridView1.ClientID%>').DataTable({ "destroy": true, "paging": false, "ordering": false, "searching": false, 'responsive': true, "AutoWidth": false });
    
            }
        </script>

    Demo:

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 20, 2020 7:27 AM
  • User-475949336 posted

    Hi Sean Fang

    I must merge your javascript before and last version and replace "divide' dropdownlist column on gridview2 by TextBox, all is good for all browers ( of laptop, PC, android, IOs), this is last code:

    function RememberValue()
    {
                    var table = $('#<%=GridView2.ClientID%>').DataTable({
                    var table = parameter1.DataTable({
                    "paging": false,
                    "ordering": true,
                    "searching": false,
                    "destroy": true,
                    'columnDefs': [
                        {                        
                            //"defaultContent": "-",
                            'targets': [1,2,3,4,5,6,7,8],
                            'render': function (data, type, row, meta) {
                                if (type === 'display') {
                                    var api = new $.fn.dataTable.Api(meta.settings);
    
                                    var $el = $('input, select, textarea', api.cell({ row: meta.row, column: meta.col }).node());
    
                                    var $html = $(data).wrap('<div/>').parent();
    
                                    if ($el.prop('tagName') === 'INPUT') {
                                        $('input', $html).attr('value', $el.val());
                                        if ($el.prop('checked')) {
                                            $('input', $html).attr('checked', 'checked');
                                        }
                                    } else if ($el.prop('tagName') === 'TEXTAREA') {
                                        $('textarea', $html).html($el.val());
    
                                    } else if ($el.prop('tagName') === 'SELECT') {
                                        $('option:selected', $html).removeAttr('selected');
                                        $('option', $html).filter(function () {
                                            return ($(this).attr('value') === $el.val());
                                        }).attr('selected', 'selected');
                                    }
    
                                    data = $html.html();
                                }
    
                                return data;
                            }
                        }
    
                    ],
                    'responsive': true
                 });
    
                // Update original input/select on change in child row
                $('#<%=GridView2.ClientID%> tbody').on('keyup change', '.child input, .child select, .child textarea', function (e) {
               
                    var $el = $(this);
                    var rowIdx = $el.closest('ul').data('dtr-index');
                    var colIdx = $el.closest('li').data('dtr-index');
                    var cell = table.cell({ row: rowIdx, column: colIdx }).node();
                    $('input, select, textarea', cell).val($el.val());
                    if ($el.is(':checked')) {
                        $('input', cell).prop('checked', true);
                    } else {
                        $('input', cell).removeProp('checked');
                    }              
            };
     function pageLoad() {
                SetTabs();
                gridView1DataTable();
                RememberValue($('#<%=GridView2.ClientID%>'), $('#<%=GridView2.ClientID%> tbody'));
    
                //Below are new Added functions for update value automatically
                bindEventBenefitDDL();
                updateTotalReceived();
                bindEventReceived();            
            }
    function gridView1DataTable()
                {
    var table = $('#<%=GridView1.ClientID%>').DataTable({ "destroy": true, "paging": false, "ordering": true, "searching": false, 'responsive': true, "AutoWidth": false });            
                }
    function bindEventBenefitDDL() {
                //Update all txtBenefit field with the value of this drop down list
                $('#<%=DropDownList_Benefit.ClientID%>').on('change', function () {
                    var value = $(this).val();
    
                    var table = $('#<%=GridView2.ClientID%>').DataTable();
                    var rowCount = table.rows().count();
                    var i;
                    for (i = 0; i < rowCount; i++) {
                        // Get all txt benefit
                        var selectorForBenefit = '#<%=GridView2.ClientID%> input[id*=txtBenefit_' + i + ']';
                        
                        // Get Country
                        var selectorForCountry = '#<%=GridView2.ClientID%> input[id*=txtCountry_' + i + ']';
                        var country = $(selectorForCountry).val();
                        if (country === "India") {
                            $(selectorForBenefit).val(value);
                        }
                    }
                    updateTotalReceived();
                });
    
    
            }
    function bindEventReceived()
             {
                $('#<%=GridView2.ClientID%> tbody').on("change", ".child input", function ()
                    {
                    updateTotalReceived();
                    });
               
                   $("[id*=txtSalary1],[id*=txtSalary2],[id*=txtDivide]").on("change", function ()
                    {
                    updateTotalReceived();
                    });            
            }
     function updateTotalReceived()
     {
                console.log("Trigger updateTotalReceived");
                var table = $('#<%=GridView2.ClientID%>').DataTable();
                var rowCount = table.rows().count();
                var totalRecieved = 0;
                var i;
                for (i = 0; i < rowCount; i++) {
                    //Get salary1
                    var selectorForSalary1 = '#<%=GridView2.ClientID%> input[id*=txtSalary1_' + i + ']';
                    var salary1 = parseInt($(selectorForSalary1).val().replace(/,/g, ''));
                    if (salary1 == "")
                        salary1 = 0;
    
                    //Get salary2
                    var selectorForSalary2 = '#<%=GridView2.ClientID%> input[id*=txtSalary2_' + i + ']';
                    var salary2 = parseInt($(selectorForSalary2).val().replace(/,/g, ''));
    
                    if (salary2 == "")
                        salary2 = 0;
                    else
                        if (parseInt(salary2) < parseInt(salary1))
                        {
                            alert("Chỉ số cuối không thể bé hơn chỉ số đầu!");
                            this.focus();
                            $(selectorForSalary2).val(0);
                        }
    
                    //Calculate salary12
                    var selectorForSalary12 = '#<%=GridView2.ClientID%> input[id*=txtSalary12_' + i + ']';
                    var salary12 = salary1 + salary2;
                    $(selectorForSalary12).val(salary12.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")); // group for currency);
                    
                    //Get divide
                    var selectorForDivide = '#<%=GridView2.ClientID%> input[id*=txtDivide_' + i + ']';
                    var divide = parseInt($(selectorForDivide).val());
    
                    //Get benefit
                    var selectorForBenefit = '#<%=GridView2.ClientID%> input[id*=txtBenefit_' + i + ']';
                    var benefit = parseInt($(selectorForBenefit).val());
                   
                    //Get received
                    var selectorForReceived = '#<%=GridView2.ClientID%> input[id*=txtReceived_' + i + ']';
                    
                    var Dropdown_Benefit = $("select[id$=DropDownList_Benefit]").val()
                    var received = (Math.round(salary12 / divide) + benefit) * Dropdown_Benefit;
                    
                    $(selectorForReceived).val(received.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")); // group for currency;
                    
                    //Increment totalRecieved
                    totalRecieved += received;
    
                }
    
                //Assign value to totalRecieved
                 $('input[id*=txtTotalReceived]').val(totalRecieved.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")); // group for currency;
    
            }

    Thanks you very much!

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 22, 2020 7:22 AM

All replies

  • User-1330468790 posted

    Hi test0101,

     

    I want when I change value in one of columns:

    - Change dropdownList Benefit then column 'Benefit' changed instant

    - change Salary1 OR Salary2 (Salary12 will change instant) OR change Salary12 OR Divide(3) OR Benefit (4) OR 'REMOVE ROW' OR 'add row'
    then Received=(1+2)/3+4 AND 'Total Received' will be changed instant.

    I WANT ALL changed instant (as using jquery), 'Total Received' must be textbox outside gridview2.

    If you want to achieve this by using Jquery, you could find more details in below code.

    To make the code more readable and easier to understand, I just focus on Jquery code about dealing with the calculation stuff. The value will not be kept after postback where I think you already had code to deal with that and "NaN" checking.

      

    Moreover, I changed some elements to <asp:label> so that the content will not be changed () as you could see that it is generated by the calculation.

    .aspx Page:

    <form id="form1" runat="server">
            <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
                <!-- Begin Addnew -->
                <div role="tabpanel" class="tab-pane" id="Addnewtab">
    
                    <div>
    
                        <label for="thangnam">
                            Month &nbsp;&nbsp;&nbsp;
                            <asp:TextBox ID="txtThangNam_addnew" Width="128px" Height="30px" runat="server" MaxLength="7"></asp:TextBox>
    
                            <ajaxToolkit:CalendarExtender ID="calendar1" ClientIDMode="Static" runat="server" TargetControlID="txtThangNam_addnew" Format="MM/yyyy"
                                DefaultView="Months" OnClientShown="onCalendarShown"
                                OnClientHidden="onCalendarHidden" PopupButtonID="imgStart" />
                        </label>
    
                        <label for="trangthai">
                            status&nbsp;
                            <asp:DropDownList ID="DropDownList_Status" OnSelectedIndexChanged="DropDownList_Status_SelectedIndexChanged" AutoPostBack="true" runat="server">
                                <asp:ListItem Text="All" Value="All"></asp:ListItem>
                                <asp:ListItem Text="status1" Value="1"></asp:ListItem>
                                <asp:ListItem Text="status2" Value="2"></asp:ListItem>
                            </asp:DropDownList>
                        </label>
    
                        <label for="lblbenefit" id="lblbenefit" runat="server">
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Benefit (4)&nbsp;
                            <asp:DropDownList ID="DropDownList_Benefit" AutoPostBack="false" runat="server">
                                <asp:ListItem Text="2" Value="2"></asp:ListItem>
                                <asp:ListItem Text="3" Value="3"></asp:ListItem>
                                <asp:ListItem Text="4" Value="4"></asp:ListItem>
                            </asp:DropDownList>
                        </label>
    
                    </div>
    
    
                    <asp:GridView ID="GridView2" CssClass="dt-responsive display" Width="100%" OnRowCommand="GridView2_RowCommand" OnRowDataBound="GridView2_RowDataBound" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#BED7F3" HeaderStyle-Height="30px" HeaderStyle-BorderStyle="None" HeaderStyle-ForeColor="#144383" Font-Names="Arial" HeaderStyle-Font-Size="13px">
    
                        <Columns>
    
                            <asp:TemplateField HeaderText="Id" HeaderStyle-Width="20px">
                                <ItemTemplate>
                                    <asp:Label ID="txtId" Width="20px" Text='<%# Eval("MyId") %>' runat="server"></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
    
                            <asp:TemplateField HeaderText="Customer Name">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtName" Text='<%# Eval("MyName") %>' Width="150px" runat="server"></asp:TextBox>
                                </ItemTemplate>
                            </asp:TemplateField>
    
                            <asp:TemplateField HeaderText="Country">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtCountry" Text='<%# Eval("MyCountry") %>' Width="100px" runat="server"></asp:TextBox>
                                </ItemTemplate>
                            </asp:TemplateField>
    
                            <asp:TemplateField HeaderText="Salary1">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtSalary1"  Text='<%# Eval("MySalary1") %>' Width="80px" runat="server"></asp:TextBox>
                                </ItemTemplate>
                            </asp:TemplateField>
    
                            <asp:TemplateField HeaderText="Salary2">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtSalary2"  Text='<%# Eval("MySalary2") %>' Width="80px" runat="server"></asp:TextBox>
                                </ItemTemplate>
                            </asp:TemplateField>
    
                            <asp:TemplateField HeaderText="Salary=(1+2)">
                                <ItemTemplate>
                                    <asp:Label ID="txtSalary12" Width="80px" runat="server"></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
    
                            <asp:TemplateField HeaderText="Divide(3)">
                                <ItemTemplate>
                                    <asp:DropDownList ID="txtDivide" runat="server" AppendDataBoundItems="true">
                                    </asp:DropDownList>
                                </ItemTemplate>
                            </asp:TemplateField>
    
                            <asp:TemplateField HeaderText="Benefit(4)">
                                <ItemTemplate>
                                    <asp:Label ID="txtBenefit" ReadOnly="true" Width="80px" runat="server"></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
    
                            <asp:TemplateField HeaderText="Received=(1+2)/3+4">
                                <ItemTemplate>
                                    <asp:Label ID="txtReceived" ReadOnly="true" Width="80px" runat="server"></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
    
                            <asp:TemplateField HeaderText="Remove" HeaderStyle-Width="50px">
                                <ItemTemplate>
                                    <asp:Button ID="bttRemoveRow" Width="100px" Text="Remove row" runat="server" CommandName="DeleteRow" CommandArgument='<%# Eval("MyId") %>'  CssClass="btn-primary"></asp:Button>
                                </ItemTemplate>
                            </asp:TemplateField>
    
                        </Columns>
                    </asp:GridView>
    
                    <div align="right">
                        <asp:Button ID="ButtonAdd" runat="server" Text="Add row" OnClick="ButtonAdd_Click" Class="btn-primary" />
                    </div>
                    <br />
                    <div align="right">
                        <label for="tungay" id="lblTotalReceived" runat="server">
                            Total Received:
                            <asp:Label ID="txtTotalReceived"  runat="server" />
                        </label>
                    </div>
    
    
                    <div align="Left">
                        <asp:Button ID="ButtonSaveAll" runat="server" Text="Save all row" OnClick="ButtonSaveAll_Click" Class="btn-primary" />
                    </div>
    
    
                </div>
                <!-- End Addnew -->
            </div>
            <script type="text/javascript">
    
                function pageLoad() {
                    RememberValue();
                    bindEventBenefitDDL();
                    updateTotalReceived();
                    bindEventReceived();
                }
    
                function bindEventBenefitDDL() {
                    $('#<%=DropDownList_Benefit.ClientID%>').on('change', function () {
                        var value = $(this).val();
                        var txtBenefitGroup = $('#<%=GridView2.ClientID%> span[id*=txtBenefit]');
                        var count = txtBenefitGroup.length - 1;
                        console.log(count);
                        txtBenefitGroup.each(function (i, element ) {
                            this.innerText = value;
                            console.log(i);
                            if (i == count) {
                                updateTotalReceived();
                            };
                            
    
                        });
                        
                    });
                    
    
                }
    
                function bindEventReceived() {
                    $("td input[id*=txtSalary1").on('change', function () {
                        updateTotalReceived();
                    });
    
                    $("td input[id*=txtSalary2]").on('change', function () {
                        updateTotalReceived();
                    })
    
                    $("td select[id*=txtDivide]").on('change', function () {
                        updateTotalReceived();
                    })
    
                }
    
                function updateTotalReceived() {
                    var total =0;
                    $('#<%=GridView2.ClientID%> span[id*=txtReceived]').each(function (i, element) {
                        updateRowReceived(this);
                        total += parseInt(this.innerText);
                    });
    
                    $('#<%=txtTotalReceived.ClientID%>').text(total);
                }
    
                function updateRowReceived(element) {
                    var row = $(element).parent().parent();
                    console.log(row);
                    var salary1 = row.find("td input[id*=txtSalary1]").val();
                    console.log('salary1:' + salary1);
                    var salary2 = row.find("td input[id*=txtSalary2]").val();
                    console.log('salary2:' + salary2);
                    var salaryTotal = parseInt(salary1) + parseInt(salary2);
                    var divide = parseInt(row.find("td select[id*=txtDivide]").val());
                    console.log('divide:' + divide);
                    var benefit = parseInt(row.find("td span[id*=txtBenefit]").text());
                    console.log('benefit:' +benefit);
    
                    element.innerText = salaryTotal / divide + benefit;
    
                }
    
                function RememberValue() {
                    var table = $('#<%=GridView2.ClientID%>').DataTable({
                        "paging": false,
                        "ordering": true,
                        "searching": false,
                        "destroy": true,
                        'columnDefs': [
                            {
                                //"defaultContent": "-",
                                'targets': [1, 2, 3, 4],
                                'render': function (data, type, row, meta) {
                                    if (type === 'display') {
                                        var api = new $.fn.dataTable.Api(meta.settings);
    
                                        var $el = $('input, select, textarea', api.cell({ row: meta.row, column: meta.col }).node());
    
                                        var $html = $(data).wrap('<div/>').parent();
    
                                        if ($el.prop('tagName') === 'INPUT') {
                                            $('input', $html).attr('value', $el.val());
                                            if ($el.prop('checked')) {
                                                $('input', $html).attr('checked', 'checked');
                                            }
                                        } else if ($el.prop('tagName') === 'TEXTAREA') {
                                            $('textarea', $html).html($el.val());
    
                                        } else if ($el.prop('tagName') === 'SELECT') {
                                            $('option:selected', $html).removeAttr('selected');
                                            $('option', $html).filter(function () {
                                                return ($(this).attr('value') === $el.val());
                                            }).attr('selected', 'selected');
                                        }
    
                                        data = $html.html();
                                    }
    
                                    return data;
                                }
                            }
    
                        ],
                        'responsive': true
                    });
    
                    // Update original input/select on change in child row
                    $('#<%=GridView2.ClientID%> tbody').on('keyup change', '.child input, .child select, .child textarea', function (e) {
    
                        var $el = $(this);
                        var rowIdx = $el.closest('ul').data('dtr-index');
                        var colIdx = $el.closest('li').data('dtr-index');
                        var cell = table.cell({ row: rowIdx, column: colIdx }).node();
                        $('input, select, textarea', cell).val($el.val());
                        if ($el.is(':checked')) {
                            $('input', cell).prop('checked', true);
                        } else {
                            $('input', cell).removeProp('checked');
                        }
                    });
                };
            </script>
    
            <script type="text/javascript">
                function onCalendarHidden() {  // Call on Addnew 
                    console.log("Begin onCalendarHidden");
                    var cal = $find("calendar1");
    
                    if (cal._monthsBody) {
                        for (var i = 0; i < cal._monthsBody.rows.length; i++) {
                            var row = cal._monthsBody.rows[i];
                            for (var j = 0; j < row.cells.length; j++) {
                                Sys.UI.DomEvent.removeHandler(row.cells[j].firstChild, "click", call);
                            }
                        }
                    }
                }
    
                function onCalendarShown() {
                    console.log("Begin onCalendarShown");
                    var cal = $find("calendar1");
    
                    cal._switchMode("months", true);
    
                    if (cal._monthsBody) {
                        for (var i = 0; i < cal._monthsBody.rows.length; i++) {
                            var row = cal._monthsBody.rows[i];
                            for (var j = 0; j < row.cells.length; j++) {
                                Sys.UI.DomEvent.addHandler(row.cells[j].firstChild, "click", call);
                            }
                        }
                    }
                }
    
                function call(eventElement) {
                    console.log("Begin call(eventElement)");
                    var target = eventElement.target;
                    switch (target.mode) {
                        case "month":
                            var cal = $find("calendar1");
                            cal._visibleDate = target.date;
                            cal.set_selectedDate(target.date);
                            //cal._switchMonth(target.date);
                            cal._blur.post(true);
                            cal.raiseDateSelectionChanged();
                            break;
                    }
                }
                function Collapse_all_rows() {
                    var table = $('#<%=GridView2.ClientID%>').DataTable();
                    table.rows('.parent').nodes().to$().find('td:first-child').trigger('click');
                    //$.each(table.rows('.parent').nodes().to$().find('td:first-child'), function (i, event) {
                    //    $(event).click();
                    //});
                }
        </script>
        </form>

    Demo:

      

    Hope this can help you.

    Best regards,

    Sean

    Thursday, April 16, 2020 8:35 AM
  • User-475949336 posted

    Hi Sean Fang

    I update your code but not effect, then I review and detect that you added to .aspx, but not mark YESLOW then I can't see.

    <form id="form1" runat="server">
            <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
                <!-- Begin Addnew -->

    When I add that lines to .aspx, it' appear error:

    Server Error in '/' Application.

    Only one instance of a ScriptManager can be added to the page.

    I removed  "<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>"  then It error:

    A page can have only one server-side Form tag.

    I think, because I use master page, in that I have <form> tag.

    And ScriptManager already in .aspx as:

    <!-- Begin List -->
    <div role="tabpanel" class="tab-pane active" id="Listtab">
    <div>
    <asp:ScriptManager id="toolScriptManageer1" runat="server" EnablePartialRendering="false"> </asp:ScriptManager>

    are you building code with my master page?

    Could you fill value to Salary=(1+2) column, I need this and recaculate when 'remove row' or add new row.

    Thursday, April 16, 2020 11:02 AM
  • User-1330468790 posted

    Hi test0101,

     

    test0101

    I update your code but not effect, then I review and detect that you added to .aspx, but not mark YESLOW then I can't see.

    I posted previous example to show you that how you could handle the instant update for the textboxes/label.

    What you need to focus on is the Javascript functions I made.

     

    test0101

    think, because I use master page, in that I have <form> tag.

    And ScriptManager already in .aspx as:

    <!-- Begin List -->
    <div role="tabpanel" class="tab-pane active" id="Listtab">
    <div>
    <asp:ScriptManager id="toolScriptManageer1" runat="server" EnablePartialRendering="false"> </asp:ScriptManager>

    are you building code with my master page?

    No, I recreate a complete new webform page with the necessary code for the "GridView2" control.

    If you find that it is difficult to integrate the javascript code, below code might be helpful. 

    I insert some "console.log()" in the code which would be helpful for you understanding the code easier (Press F12 in browser).

     

    .aspx Page: Scroll down to pageload() function.

    (No any change on your code except new added javascript functions)

    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <div class="tab-content" style="width: auto; border: none; font-family: Arial; font-size: larger; color: #1443AB; font-weight: bold; text-align: center; padding: 1px; margin: 1px">
                    GRIDVIEW
                </div>
                <div class="panel panel-default" style="width: auto; padding: 6px; margin: 6px">
    
                    <div id="dvTab">
    
                        <ul class="nav nav-tabs" role="tablist" style="font-weight: bold">
                            <li runat="server" id="idListtab" class="active"><a href="#Listtab" style="outline: none" aria-controls="Listtab" role="tab" data-toggle="tab">LIST</a></li>
                            <li runat="server" id="idAddnewtab"><a href="#Addnewtab" style="outline: none" aria-controls="Addnewtab" role="tab" data-toggle="tab">ADD NEW</a></li>
                            <li runat="server" id="idEdittab"><a href="#Edittab" style="outline: none" aria-controls="Edittab" role="tab" data-toggle="tab">EDIT</a></li>
                            <li runat="server" id="idViewtab"><a href="#Viewtab" style="outline: none" aria-controls="Viewtab" role="tab" data-toggle="tab">VIEW</a></li>
    
                        </ul>
    
                        <div class="tab-content" style="padding-top: 5px">
    
                            <!-- Begin List -->
                            <div role="tabpanel" class="tab-pane active" id="Listtab">
    
                                <div>
    
                                    <asp:ScriptManager ID="toolScriptManageer1" runat="server" EnablePartialRendering="false">
                                    </asp:ScriptManager>
    
                                    <label for="tungay">
                                        From &nbsp;&nbsp;&nbsp;
                                        <asp:TextBox ID="txtTungay" Width="128px" Height="30px" runat="server" MaxLength="10" AutoPostBack="true"></asp:TextBox>
                                        <ajaxtoolkit:calendarextender id="Calendarfromdate" popupbuttonid="imgPopup" runat="server" targetcontrolid="txtTungay" format="dd/MM/yyyy" />
                                    </label>
    
    
                                    <label for="denngay">
                                        To &nbsp;
    
                                        <asp:TextBox ID="txtDenngay" Width="128px" Height="30px" AutoPostBack="true" runat="server" MaxLength="10"></asp:TextBox>
                                        <ajaxtoolkit:calendarextender id="Calendartodate" popupbuttonid="imgPopup" runat="server" targetcontrolid="txtDenngay" format="dd/MM/yyyy" />
    
                                    </label>
    
                                    <label for="trangthai">
                                        Status&nbsp;
                                        <asp:DropDownList ID="txtTrangthai" Width="128px" Height="30px" AutoPostBack="true" runat="server">
                                            <asp:ListItem Text="All" Value="All"></asp:ListItem>
                                            <asp:ListItem Text="status1" Value="1"></asp:ListItem>
                                            <asp:ListItem Text="status2" Value="2"></asp:ListItem>
                                        </asp:DropDownList>
                                    </label>
    
                                </div>
                                <br />
    
                                <asp:GridView ID="GridView1" CssClass="dt-responsive" class="display" Width="100%" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#BED7F3" HeaderStyle-Height="30px" HeaderStyle-BorderStyle="None" HeaderStyle-ForeColor="#144383" Font-Names="Arial" HeaderStyle-Font-Size="13px">
    
                                    <Columns>
                                        <asp:BoundField DataField="Id" HeaderText="Customer Id" />
                                        <asp:BoundField DataField="Name" HeaderText="Customer Name" />
                                        <asp:BoundField DataField="Country" HeaderText="Country" />
    
                                        <asp:TemplateField HeaderText="Salary">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtSalary" Text='<%# Eval("Salary") %>' Width="80px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:BoundField DataField="Job" HeaderText="Job" />
    
                                    </Columns>
                                </asp:GridView>
    
                                <input type="hidden" runat="server" id="hidMaHDDV" />
    
                            </div>
                            <!-- End List -->
    
    
                            <!-- Begin Addnew -->
                            <div role="tabpanel" class="tab-pane" id="Addnewtab">
    
                                <div>
    
                                    <label for="thangnam">
                                        Month &nbsp;&nbsp;&nbsp;
                                        <asp:TextBox ID="txtThangNam_addnew" Width="128px" Height="30px" runat="server" MaxLength="7"></asp:TextBox>
    
                                        <ajaxtoolkit:calendarextender id="calendar1" clientidmode="Static" runat="server" targetcontrolid="txtThangNam_addnew" format="MM/yyyy"
                                            defaultview="Months" onclientshown="onCalendarShown"
                                            onclienthidden="onCalendarHidden" popupbuttonid="imgStart" />
                                    </label>
    
                                    <label for="trangthai">
                                        status&nbsp;
                                        <asp:DropDownList ID="DropDownList_Status" OnSelectedIndexChanged="DropDownList_Status_selectedIndexChanged" AutoPostBack="true" runat="server">
                                            <asp:ListItem Text="All" Value="All"></asp:ListItem>
                                            <asp:ListItem Text="status1" Value="1"></asp:ListItem>
                                            <asp:ListItem Text="status2" Value="2"></asp:ListItem>
                                        </asp:DropDownList>
                                    </label>
    
                                    <label for="lblbenefit" id="lblbenefit" runat="server">
                                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Benefit (4)&nbsp;
                                        <asp:DropDownList ID="DropDownList_Benefit" runat="server">
                                            <asp:ListItem Text="2" Value="2"></asp:ListItem>
                                            <asp:ListItem Text="3" Value="3"></asp:ListItem>
                                            <asp:ListItem Text="4" Value="4"></asp:ListItem>
                                        </asp:DropDownList>
                                    </label>
    
                                </div>
    
    
                                <asp:GridView ID="GridView2" CssClass="dt-responsive" class="display" Width="100%" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#BED7F3" HeaderStyle-Height="30px" HeaderStyle-BorderStyle="None" HeaderStyle-ForeColor="#144383" Font-Names="Arial" HeaderStyle-Font-Size="13px">
    
                                    <Columns>
    
                                        <asp:TemplateField HeaderText="Id" HeaderStyle-Width="20px">
                                            <ItemTemplate>
                                                <asp:Label ID="txtId" Width="20px" Text='<%# Eval("MyId") %>' runat="server"></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Customer Name">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtName" Text='<%# Eval("MyName") %>' Width="150px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="CountryCode" Visible="false">
                                            <ItemTemplate>
                                                <asp:Label ID="txtCountryCode" Text='<%# Eval("CountryCode") %>' runat="server" Visible="false"></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
    
                                        <asp:TemplateField HeaderText="Country">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtCountry" Text='<%# Eval("MyCountry") %>' Width="100px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Salary1">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtSalary1" onkeyup="isNumberKey(this);" Text='<%# Eval("MySalary1") %>' Width="80px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Salary2">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtSalary2" onkeyup="isNumberKey(this);" Text='<%# Eval("MySalary2") %>' Width="80px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Salary=(1+2)">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtSalary12" onkeyup="isNumberKey(this);" Text='<%# Eval("MySalary12") %>' Width="80px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Divide(3)">
                                            <ItemTemplate>
                                                <asp:DropDownList ID="txtDivide" runat="server" AppendDataBoundItems="true">
                                                </asp:DropDownList>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Benefit(4)">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtBenefit" ReadOnly="true" Text='<%# Eval("MyBenefit") %>' Width="80px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Received=(1+2)/3+4">
                                            <ItemTemplate>
                                                <asp:TextBox ID="txtReceived" ReadOnly="true" Text='<%# Eval("MyReceived") %>' Width="80px" runat="server"></asp:TextBox>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <asp:TemplateField HeaderText="Remove" HeaderStyle-Width="50px">
                                            <ItemTemplate>
                                                <asp:Button ID="bttRemoveRow" Width="100px" Text="Remove row" runat="server" OnClick="bttRemoveRow_Click" Class="btn-primary"></asp:Button>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                    </Columns>
                                </asp:GridView>
    
                                <div align="right">
                                    <asp:Button ID="ButtonAdd" runat="server" Text="Add row" OnClick="ButtonAdd_Click" Class="btn-primary" />
                                </div>
                                <br />
                                <div align="right">
                                    <label for="tungay" id="lblTotalReceived" runat="server">
                                        Total Received:
                                        <asp:TextBox ID="txtTotalReceived"  runat="server" />
                                    </label>
                                </div>
    
    
                                <div align="Left">
                                    <asp:Button ID="ButtonSaveAll" runat="server" Text="Save all row" OnClick="ButtonSaveAll_Click" Class="btn-primary" />
                                </div>
    
    
                            </div>
                            <!-- End Addnew -->
    
                            <!-- Begin Edit -->
                            <div role="tabpanel" class="tab-pane" id="Edittab">
                                Edit
                            </div>
                            <!-- End Edit -->
    
    
                            <!-- Begin View -->
                            <div role="tabpanel" class="tab-pane" id="Viewtab">
                                View
                            </div>
                            <!-- End View -->
    
                        </div>
                    </div>
                </div>
    
                <asp:HiddenField ID="HiddenTab" runat="server" />
    
            </ContentTemplate>
        </asp:UpdatePanel>
    
        <!-- Panel End-->
    
        <script type="text/javascript">
    
            function isNumberKey(i) {
                if (i.value.length > 0) {
                    i.value = i.value.replace(/[^\d]+/g, ''); // Only number
                    i.value = i.value.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); // group for currency
                }
    
            }
    
            function RememberValue() {
                var table = $('#<%=GridView2.ClientID%>').DataTable({
            "paging": false,
            "ordering": true,
            "searching": false,
            "destroy": true,
            'columnDefs': [
                {
                    //"defaultContent": "-",
                    'targets': [1, 2, 3, 4],
                    'render': function (data, type, row, meta) {
                        if (type === 'display') {
                            var api = new $.fn.dataTable.Api(meta.settings);
    
                            var $el = $('input, select, textarea', api.cell({ row: meta.row, column: meta.col }).node());
    
                            var $html = $(data).wrap('<div/>').parent();
    
                            if ($el.prop('tagName') === 'INPUT') {
                                $('input', $html).attr('value', $el.val());
                                if ($el.prop('checked')) {
                                    $('input', $html).attr('checked', 'checked');
                                }
                            } else if ($el.prop('tagName') === 'TEXTAREA') {
                                $('textarea', $html).html($el.val());
    
                            } else if ($el.prop('tagName') === 'SELECT') {
                                $('option:selected', $html).removeAttr('selected');
                                $('option', $html).filter(function () {
                                    return ($(this).attr('value') === $el.val());
                                }).attr('selected', 'selected');
                            }
    
                            data = $html.html();
                        }
    
                        return data;
                    }
                }
    
            ],
            'responsive': true
        });
    
        // Update original input/select on change in child row
        $('#<%=GridView2.ClientID%> tbody').on('keyup change', '.child input, .child select, .child textarea', function (e) {
    
                    var $el = $(this);
                    var rowIdx = $el.closest('ul').data('dtr-index');
                    var colIdx = $el.closest('li').data('dtr-index');
                    var cell = table.cell({ row: rowIdx, column: colIdx }).node();
                    $('input, select, textarea', cell).val($el.val());
                    if ($el.is(':checked')) {
                        $('input', cell).prop('checked', true);
                    } else {
                        $('input', cell).removeProp('checked');
                    }
                });
            };
    
    
    
            function SetTabs() {
                var tabName = $("[id*=HiddenTab]").val() != "" ? $("[id*=HiddenTab]").val() : "Listtab";
                $('#dvTab a[href="#' + tabName + '"]').tab('show');
                $('#dvTab a').on('shown.bs.tab', function (e) {
                    $("[id*=HiddenTab]").val($(this).attr("href").replace("#", ""));
                    $($.fn.dataTable.tables(true)).DataTable()
                        .columns.adjust()
                        .responsive.recalc();
                });
    
            };
    
        </script>
    
        <script type="text/javascript">
    
            function pageLoad() {
                SetTabs();
                gridView1DataTable();
                RememberValue();
                //Below are new Added functions for update value automatically
                bindEventBenefitDDL();
                updateTotalReceived();
                bindEventReceived();
    
            }
    
    
            function bindEventBenefitDDL() {
                //Update all txtBenefit field with the value of this drop down list
                $('#<%=DropDownList_Benefit.ClientID%>').on('change', function () {
                     var value = $(this).val();
                    var txtBenefitGroup = $('#<%=GridView2.ClientID%> input[id*=txtBenefit]');
                        var count = txtBenefitGroup.length - 1;
                        //Update each txtBenefit and update the TotalReceived input field after the update completed
                        txtBenefitGroup.each(function (i, element) {
                            $(this).val(value);
                            if (i == count) {
                                updateTotalReceived();
                            };
                        });
    
                    });
    
    
            }
    
            function bindEventReceived() {
                // Bind change event to salary1
                $("td input[id*=txtSalary1").on('change', function () {
                    updateTotalReceived();
                });
    
                // Bind change event to salary2
                $("td input[id*=txtSalary2]").on('change', function () {
                    updateTotalReceived();
                })
    
                // Bind change event to divide
                $("td select[id*=txtDivide]").on('change', function () {
                    updateTotalReceived();
                })
    
            }
    
            function updateTotalReceived() {
                var total = 0;
                //Sum for txtReceiveds in each row
                $('#<%=GridView2.ClientID%> input[id*=txtReceived]').each(function (i, element) {
                        updateRowReceived(this);
                        total += parseInt($(this).val());
                    });
    
                    $('#<%=txtTotalReceived.ClientID%>').val(total);
            }
    
            // You can check the value through the console. If you don't need these consoles anymore, delete it
            function updateRowReceived(element) {
    //Find the current row of the element (txtReceived) var row = $(element).parent().parent(); console.log(row); //Find salary1 in this row var salary1 = row.find("td input[id*=txtSalary1]").val().replace(",",""); console.log('salary1:' + salary1); //Find salary2 in this row var salary2 = row.find("td input[id*=txtSalary2]").val().replace(",",""); console.log('salary2:' + salary2); //Calculate salary1 + salary2 and fil it into salary12 var salaryTotal = parseInt(salary1) + parseInt(salary2); row.find("td input[id*=txtSalary12]").val(salaryTotal); //Get divide value var divide = parseInt(row.find("td select[id*=txtDivide]").val()); console.log('divide:' + divide); //Get benefit value var benefit = parseInt(row.find("td input[id*=txtBenefit]").val()); console.log('benefit:' + benefit); //Fill the txtReceived with the result of calculations $(element).val(salaryTotal / divide + benefit); } function gridView1DataTable() { var table = $('#<%=GridView1.ClientID%>').DataTable({ "destroy": true, "paging": false, "ordering": false, "searching": false, 'responsive': true, "AutoWidth": false }); } </script> <script type="text/javascript"> function onCalendarHidden() { // Call on Addnew var cal = $find("calendar1"); if (cal._monthsBody) { for (var i = 0; i < cal._monthsBody.rows.length; i++) { var row = cal._monthsBody.rows[i]; for (var j = 0; j < row.cells.length; j++) { Sys.UI.DomEvent.removeHandler(row.cells[j].firstChild, "click", call); } } } } function onCalendarShown() { var cal = $find("calendar1"); cal._switchMode("months", true); if (cal._monthsBody) { for (var i = 0; i < cal._monthsBody.rows.length; i++) { var row = cal._monthsBody.rows[i]; for (var j = 0; j < row.cells.length; j++) { Sys.UI.DomEvent.addHandler(row.cells[j].firstChild, "click", call); } } } } function call(eventElement) { var target = eventElement.target; switch (target.mode) { case "month": var cal = $find("calendar1"); cal._visibleDate = target.date; cal.set_selectedDate(target.date); //cal._switchMonth(target.date); cal._blur.post(true); cal.raiseDateSelectionChanged(); break; } } </script> </asp:Content>

    Demo:

     

    Note that I didn't do any format stuff except removing the comma for the currency value of "salary1" and "salary2".

    You could modify the code to achieve whatever format you want.

     

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 17, 2020 5:20 AM
  • User-475949336 posted

    Hi Sean Fang

    I updated, it run good when all columns no hidden, if I resize brower for hidden colums: salary1, salary2..., when I change value it not Recaculate salary12, txtReceived and total.

    pls check help me!

    Friday, April 17, 2020 6:41 AM
  • User-475949336 posted

    Hi Sean Fang

    I spent alot of time to find solution, that don't use javascript, example use OnTextChanged ="TextBox_TextChanged", but can't satisfy, because it resquest must postback.

    So, I'm waiting you solve the issue when columns salary1, salary2 hidden then don't caculate received and total.

    Friday, April 17, 2020 9:07 AM
  • User-1330468790 posted

    Hi test0101,

     

    The problem is a bit complicated when the responsive elements were added in the page.

    Sorry that I didn't put the responsive elements under consideration.

      

    You could use below code to refresh the values no matter the page is in responsive size or regular size.

    I didn't change the HTML element. The only thing we need to do is modify the JavaScript code.

    Script:

     

    <script type="text/javascript">
    
            function isNumberKey(i) {
                if (i.value.length > 0) {
                    i.value = i.value.replace(/[^\d]+/g, ''); // Only number
                    i.value = i.value.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); // group for currency
                }
    
            }
    
            function RememberValue() {
                var table = $('#<%=GridView2.ClientID%>').DataTable({
                    "paging": false,
                    "ordering": true,
                    "searching": false,
                    "destroy": true,
                    'columnDefs': [
                        {
                            //"defaultContent": "-",
                            'targets': [1, 2, 3, 4,5,6,7,8],
                            'render': function (data, type, row, meta) {
                                if (type === 'display') {
                                    var api = new $.fn.dataTable.Api(meta.settings);
    
                                    var $el = $('input, select, textarea', api.cell({ row: meta.row, column: meta.col }).node());
    
                                    var $html = $(data).wrap('<div/>').parent();
    
                                    if ($el.prop('tagName') === 'INPUT') {
                                        $('input', $html).attr('value', $el.val());
                                        if ($el.prop('checked')) {
                                            $('input', $html).attr('checked', 'checked');
                                        }
                                    } else if ($el.prop('tagName') === 'TEXTAREA') {
                                        $('textarea', $html).html($el.val());
    
                                    } else if ($el.prop('tagName') === 'SELECT') {
                                        $('option:selected', $html).removeAttr('selected');
                                        $('option', $html).filter(function () {
                                            return ($(this).attr('value') === $el.val());
                                        }).attr('selected', 'selected');
                                    }
    
                                    data = $html.html();
                                }
    
                                return data;
                            }
                        }
    
                    ],
                    'responsive': true
                });
    
               // Update original input/select on change in child row
                $('#<%=GridView2.ClientID%> tbody').on('keyup change', '.child input, .child select, .child textarea', function (e) {
                    
                    var $el = $(this);
                    var rowIdx = $el.closest('ul').data('dtr-index');
                    var colIdx = $el.closest('li').data('dtr-index');
                    var cell = table.cell({ row: rowIdx, column: colIdx }).node();
                    $('input, select, textarea', cell).val($el.val());
    
                    console.log($el.val() + "   XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
                    if ($el.is(':checked')) {
                        $('input', cell).prop('checked', true);
                    } else {
                        $('input', cell).removeProp('checked');
                    }
    
                    updateTotalReceived();
                });
    
    
                table.on('responsive-display', function (e, datatable, row, showHide, update) {
                    
                    updateTotalReceived();
                } );
    
            };
    
    
    
            function SetTabs() {
                var tabName = $("[id*=HiddenTab]").val() != "" ? $("[id*=HiddenTab]").val() : "Listtab";
                $('#dvTab a[href="#' + tabName + '"]').tab('show');
                $('#dvTab a').on('shown.bs.tab', function (e) {
                    $("[id*=HiddenTab]").val($(this).attr("href").replace("#", ""));
                    $($.fn.dataTable.tables(true)).DataTable()
                        .columns.adjust()
                        .responsive.recalc();
                });
    
            };
    
        </script>

    Another Script block.

    <script type="text/javascript">
    
            function pageLoad() {
                SetTabs();
                gridView1DataTable();
                RememberValue();
                //Below are new Added functions for update value automatically
                bindEventBenefitDDL();
    
            }
    
            //Bind DDL to new generate benefit
            function bindEventBenefitDDL() {
                //Update all txtBenefit field with the value of this drop down list
                $('#<%=DropDownList_Benefit.ClientID%>').on('change', function () {
                    var value = $(this).val();
                    var txtBenefitGroup = $('#<%=GridView2.ClientID%> input[id*=txtBenefit]');
                    var count = txtBenefitGroup.length - 1;
                    //Update each txtBenefit and update the TotalReceived input field after the update completed
                    txtBenefitGroup.each(function (i, element) {
                        $(this).val(value);
                        if (i == count) {
                            updateTotalReceived();
                        };
                    });
    
                });
    
    
            }
    
            //Calculate the total received
            function updateTotalReceived() {
                console.log("Trigger updateTotalReceived");
                var table = $('#<%=GridView2.ClientID%>').DataTable();
                var rowCount = table.rows().count();
                var totalRecieved = 0;
                var i;
                for (i = 0; i < rowCount; i++) {
                    //Get salary1
                    var selectorForSalary1 = '#<%=GridView2.ClientID%> input[id*=txtSalary1_' + i + ']';
                    var salary1 = parseInt($(selectorForSalary1).val().replace(",", ""));
    
                    //Get salary2
                    var selectorForSalary2 = '#<%=GridView2.ClientID%> input[id*=txtSalary2_' + i + ']';
                    var salary2 = parseInt($(selectorForSalary2).val().replace(",", ""));
    
                    //Calculate salary12
                    var selectorForSalary12 = '#<%=GridView2.ClientID%> input[id*=txtSalary12_' + i + ']';
                    var salary12 = salary1 + salary2;
                    $(selectorForSalary12).val(salary12);
    
    
                    //Get divide
                    var selectorForDivide = '#<%=GridView2.ClientID%> select[id*=txtDivide_' + i + ']';
                    var divide = parseInt($(selectorForDivide).val());
    
                    //Get benefit
                    var selectorForBenefit = '#<%=GridView2.ClientID%> input[id*=txtBenefit_' + i + ']';
                    var benefit = parseInt($(selectorForBenefit).val());
                   
                    //Get received
                    var selectorForReceived = '#<%=GridView2.ClientID%> input[id*=txtReceived_' + i + ']';
                    var received = (salary12 / divide) + benefit;
                    $(selectorForReceived).val(received);
                    
                    //Increment totalRecieved
                    totalRecieved += received;
    
                }
    
                //Assign value to totalRecieved
                $('input[id*=txtTotalReceived]').val(totalRecieved);
    
            }
    
    function gridView1DataTable() {
                var table = $('#<%=GridView1.ClientID%>').DataTable({ "destroy": true, "paging": false, "ordering": false, "searching": false, 'responsive': true, "AutoWidth": false });
    
            }
        </script>

    Demo:

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 20, 2020 7:27 AM
  • User-475949336 posted

    Hi Sean Fang

    Pls help me edit this function in order to change only 'benefis' columns when 'country' equal 'India'

    function bindEventBenefitDDL() {
                //Update all txtBenefit field with the value of this drop down list
                $('#<%=DropDownList_Benefit.ClientID%>').on('change', function () {
                    var value = $(this).val();
                    var txtBenefitGroup = $('#<%=GridView2.ClientID%> input[id*=txtBenefit]');
                    var count = txtBenefitGroup.length - 1;
                    //Update each txtBenefit and update the TotalReceived input field after the update completed
                    txtBenefitGroup.each(function (i, element)
    {
    var row = $(element).closest("tr");
    var country = row.find($("[id*=txtCountry]")).val();
    if (country == "India")
    { $(this).val(value);
    }
    if (i == count) { updateTotalReceived(); }; }); }); }
    Monday, April 20, 2020 7:39 AM
  • User-475949336 posted

    Hi Sean Fang

    I tested with full your scipt, it only caculate when salay1, salary2 is hidden, it don't caculate if all columns are visiable.

    So, with your script before, i modified it good for all, but I have a bit issue is can't edit function in order to change only 'benefis' columns when 'country' equal 'India'

    this is edit scipt:

    function pageLoad() {
    SetTabs();
    gridView1DataTable();
    RememberValue();

    //Below are new Added functions for update value automatically
    bindEventBenefitDDL();
    updateTotalReceived();
    bindEventReceived();
    }

    function bindEventBenefitDDL() {
    //Update all txtBenefit field with the value of this drop down list
    $('#<%=DropDownList_Benefit.ClientID%>').on('change', function () {
    var value = $(this).val();

    var txtBenefitGroup = $('#<%=GridView2.ClientID%> input[id*=txtBenefit]');
    var count = txtBenefitGroup.length - 1;

    // Update each txtBenefit and update the TotalReceived input field after the update completed
    txtBenefitGroup.each(function (i, element)
    {
    // var row = $(element).parent().parent();
    var row = $(element).closest("tr");
    // var row = $(element).closest("tr");
    // var country = row.find("td input[id*=txtCountry]").val();
    var country = row.find($("[id*=txtCountry]")).val();

    if (country == "India")
    {
    // $(this).val(value);
    row.find("[id*=txtBenefit]").val(value);
    };

    if (i == count) {
    updateTotalReceived();
    };
    });
    });
    }

    function bindEventReceived()
    {
    $('#<%=GridView2.ClientID%> tbody').on("change", ".child input", function ()
    {
    updateTotalReceived();
    });

    // $("td input[id*=txtSalary1").on('change', function () {
    $("[id*=txtSalary1],[id*=txtSalary2],[id*=txtDivide]").on("change", function ()
    {
    updateTotalReceived();
    });
    }

    function updateTotalReceived() {
    var total = 0;
    //Sum for txtReceiveds in each row
    $('#<%=GridView2.ClientID%> input[id*=txtReceived]').each(function (i, element)
    {
    // updateRowReceived(this);
    updateRowReceived($(this).closest("tr"));
    total += parseInt($(this).val());
    });
    $('#<%=txtTotalReceived.ClientID%>').val(total);
    }

    // function updateRowReceived(element) {
    function updateRowReceived(row){

    // Find the current row of the element (txtReceived)
    // var row = $(element).parent().parent();

    // Find salary1 in this row
    // var salary1 = row.find("td input[id*=txtSalary1]").val().replace(",","");
    var salary1 = $(row).find($("[id*=txtSalary1]")).val().replace(/,/g, '');
    if (salary1 == "")
    salary1=0;


    // var salary2 = row.find("td input[id*=txtSalary2]").val().replace(",","");
    var salary2 = $(row).find($("[id*=txtSalary2]")).val().replace(/,/g, '');

    if (salary2 == "")
    salary2 = 0;
    else
    if (parseFloat(salary2) < parseFloat(salary1))
    {
    alert("Chỉ số cuối không thể bé hơn chỉ số đầu!");
    this.focus();
    $(row).find($("[id*=txtSalary2]")).val("");
    }


    var salaryTotal = parseFloat(salary1) + parseFloat(salary2);

    // row.find("td input[id*=txtSalary12]").val(salaryTotal);
    $(row).find("[id*=txtSalary12]").val(salaryTotal).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); // group for currency;;

    // var divide = parseInt(row.find("td select[id*=txtDivide]").val());
    var divide = parseInt($(row).find($("[id*=txtDivide]")).val());

    // var benefit = parseInt(row.find("td input[id*=txtBenefit]").val());
    var benefit = parseInt($(row).find($("[id*=txtBenefit]")).val());

    // $(element).val(salaryTotal / divide + benefit);
    $(row).find("[id*=txtReceived]").val(salaryTotal / divide + benefit).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); // group for currency;;
    }

    pls help me edit function mark red

    Monday, April 20, 2020 7:59 AM
  • User-1330468790 posted

    Hi test0101,

     

    Just rewrite the whole bindEventBenefitDDL() function, you should bear in mind that, if the layout and elements will be changed, you should use 'id' or other identifier to look for the element instead of using sibling.

     

    Solution:

    //Bind DDL to new generate benefit
            function bindEventBenefitDDL() {
                //Update all txtBenefit field with the value of this drop down list
                $('#<%=DropDownList_Benefit.ClientID%>').on('change', function () {
                    var value = $(this).val();
    
                    var table = $('#<%=GridView2.ClientID%>').DataTable();
                    var rowCount = table.rows().count();
                    var i;
                    for (i = 0; i < rowCount; i++) {
    // Get all txt benefit var selectorForBenefit = '#<%=GridView2.ClientID%> input[id*=txtBenefit_' + i + ']';
    // Get Country var selectorForCountry = '#<%=GridView2.ClientID%> input[id*=txtCountry_' + i + ']'; var country = $(selectorForCountry).val(); if (country === "India") { $(selectorForBenefit).val(value); } } updateTotalReceived(); }); }

      

    The base of above code is that you have defined a function to update the data for the original datatable rows so that you could always check the first value returned by the Jquery selector.

      

    Best regards,

    Sean

    Monday, April 20, 2020 11:04 AM
  • User-475949336 posted

    ok Sean Fang, I will update on main project and test

    Monday, April 20, 2020 11:44 AM
  • User-475949336 posted

    Hi Sean Fang

    I update all script as link1  and link2  to main project, I tested on laptop, PC, android is good, but on Ipad's Safari is no (if change salary1, salary2 then Received don't caculate (because Received is hidden), while salary12 is changed (because salary12 no hidden).  And if change benefis dropdownlist then benefis columns is changed

    Tuesday, April 21, 2020 3:00 AM
  • User-1330468790 posted

    Hi test0101,

     

    but on Ipad's Safari is no (if change salary1, salary2 then Received don't caculate (because Received is hidden), while salary12 is changed (because salary12 no hidden). 

    It is a bit confusing for me about the content you put in the parentheses. The javascript functions (last version) I provide you use the hard coding to fetch the HTML element so it should not be bothered by visibility. 

    And if change benefis dropdownlist then benefis columns is changed

    Do you mean that the benefits text boxes do not follow the "India-equivalent" rule?

     

    I recommend you a GIF-maker that could produce gif file from your screen. 

    https://www.screentogif.com/ 

    You could check if it fulfills security/guidance from your side and if it does, you could use this tool to show me the problem.

     

    Best regards,

    Sean

    Wednesday, April 22, 2020 5:33 AM
  • User-475949336 posted

    Hi Sean Fang

    I must merge your javascript before and last version and replace "divide' dropdownlist column on gridview2 by TextBox, all is good for all browers ( of laptop, PC, android, IOs), this is last code:

    function RememberValue()
    {
                    var table = $('#<%=GridView2.ClientID%>').DataTable({
                    var table = parameter1.DataTable({
                    "paging": false,
                    "ordering": true,
                    "searching": false,
                    "destroy": true,
                    'columnDefs': [
                        {                        
                            //"defaultContent": "-",
                            'targets': [1,2,3,4,5,6,7,8],
                            'render': function (data, type, row, meta) {
                                if (type === 'display') {
                                    var api = new $.fn.dataTable.Api(meta.settings);
    
                                    var $el = $('input, select, textarea', api.cell({ row: meta.row, column: meta.col }).node());
    
                                    var $html = $(data).wrap('<div/>').parent();
    
                                    if ($el.prop('tagName') === 'INPUT') {
                                        $('input', $html).attr('value', $el.val());
                                        if ($el.prop('checked')) {
                                            $('input', $html).attr('checked', 'checked');
                                        }
                                    } else if ($el.prop('tagName') === 'TEXTAREA') {
                                        $('textarea', $html).html($el.val());
    
                                    } else if ($el.prop('tagName') === 'SELECT') {
                                        $('option:selected', $html).removeAttr('selected');
                                        $('option', $html).filter(function () {
                                            return ($(this).attr('value') === $el.val());
                                        }).attr('selected', 'selected');
                                    }
    
                                    data = $html.html();
                                }
    
                                return data;
                            }
                        }
    
                    ],
                    'responsive': true
                 });
    
                // Update original input/select on change in child row
                $('#<%=GridView2.ClientID%> tbody').on('keyup change', '.child input, .child select, .child textarea', function (e) {
               
                    var $el = $(this);
                    var rowIdx = $el.closest('ul').data('dtr-index');
                    var colIdx = $el.closest('li').data('dtr-index');
                    var cell = table.cell({ row: rowIdx, column: colIdx }).node();
                    $('input, select, textarea', cell).val($el.val());
                    if ($el.is(':checked')) {
                        $('input', cell).prop('checked', true);
                    } else {
                        $('input', cell).removeProp('checked');
                    }              
            };
     function pageLoad() {
                SetTabs();
                gridView1DataTable();
                RememberValue($('#<%=GridView2.ClientID%>'), $('#<%=GridView2.ClientID%> tbody'));
    
                //Below are new Added functions for update value automatically
                bindEventBenefitDDL();
                updateTotalReceived();
                bindEventReceived();            
            }
    function gridView1DataTable()
                {
    var table = $('#<%=GridView1.ClientID%>').DataTable({ "destroy": true, "paging": false, "ordering": true, "searching": false, 'responsive': true, "AutoWidth": false });            
                }
    function bindEventBenefitDDL() {
                //Update all txtBenefit field with the value of this drop down list
                $('#<%=DropDownList_Benefit.ClientID%>').on('change', function () {
                    var value = $(this).val();
    
                    var table = $('#<%=GridView2.ClientID%>').DataTable();
                    var rowCount = table.rows().count();
                    var i;
                    for (i = 0; i < rowCount; i++) {
                        // Get all txt benefit
                        var selectorForBenefit = '#<%=GridView2.ClientID%> input[id*=txtBenefit_' + i + ']';
                        
                        // Get Country
                        var selectorForCountry = '#<%=GridView2.ClientID%> input[id*=txtCountry_' + i + ']';
                        var country = $(selectorForCountry).val();
                        if (country === "India") {
                            $(selectorForBenefit).val(value);
                        }
                    }
                    updateTotalReceived();
                });
    
    
            }
    function bindEventReceived()
             {
                $('#<%=GridView2.ClientID%> tbody').on("change", ".child input", function ()
                    {
                    updateTotalReceived();
                    });
               
                   $("[id*=txtSalary1],[id*=txtSalary2],[id*=txtDivide]").on("change", function ()
                    {
                    updateTotalReceived();
                    });            
            }
     function updateTotalReceived()
     {
                console.log("Trigger updateTotalReceived");
                var table = $('#<%=GridView2.ClientID%>').DataTable();
                var rowCount = table.rows().count();
                var totalRecieved = 0;
                var i;
                for (i = 0; i < rowCount; i++) {
                    //Get salary1
                    var selectorForSalary1 = '#<%=GridView2.ClientID%> input[id*=txtSalary1_' + i + ']';
                    var salary1 = parseInt($(selectorForSalary1).val().replace(/,/g, ''));
                    if (salary1 == "")
                        salary1 = 0;
    
                    //Get salary2
                    var selectorForSalary2 = '#<%=GridView2.ClientID%> input[id*=txtSalary2_' + i + ']';
                    var salary2 = parseInt($(selectorForSalary2).val().replace(/,/g, ''));
    
                    if (salary2 == "")
                        salary2 = 0;
                    else
                        if (parseInt(salary2) < parseInt(salary1))
                        {
                            alert("Chỉ số cuối không thể bé hơn chỉ số đầu!");
                            this.focus();
                            $(selectorForSalary2).val(0);
                        }
    
                    //Calculate salary12
                    var selectorForSalary12 = '#<%=GridView2.ClientID%> input[id*=txtSalary12_' + i + ']';
                    var salary12 = salary1 + salary2;
                    $(selectorForSalary12).val(salary12.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")); // group for currency);
                    
                    //Get divide
                    var selectorForDivide = '#<%=GridView2.ClientID%> input[id*=txtDivide_' + i + ']';
                    var divide = parseInt($(selectorForDivide).val());
    
                    //Get benefit
                    var selectorForBenefit = '#<%=GridView2.ClientID%> input[id*=txtBenefit_' + i + ']';
                    var benefit = parseInt($(selectorForBenefit).val());
                   
                    //Get received
                    var selectorForReceived = '#<%=GridView2.ClientID%> input[id*=txtReceived_' + i + ']';
                    
                    var Dropdown_Benefit = $("select[id$=DropDownList_Benefit]").val()
                    var received = (Math.round(salary12 / divide) + benefit) * Dropdown_Benefit;
                    
                    $(selectorForReceived).val(received.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")); // group for currency;
                    
                    //Increment totalRecieved
                    totalRecieved += received;
    
                }
    
                //Assign value to totalRecieved
                 $('input[id*=txtTotalReceived]').val(totalRecieved.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")); // group for currency;
    
            }

    Thanks you very much!

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 22, 2020 7:22 AM