Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > บทความจากสมาชิก > Auto calculate row sub-total and grand total by jQuery within ASP.NET



 
Clound SSD Virtual Server

Auto calculate row sub-total and grand total by jQuery within ASP.NET

auto calculate row sub-total and grand total with

Code (ASP)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewBasic.aspx.cs" Inherits="Pages_StandDardControl_Grid_GridViewBasic" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.min.js" type="text/javascript"></script>
    <style>
        .DisbledLabel
        {
            color: Gray;
        }
        .EnabledLabel
        {
            color: Black;
        }
        
        .PricePerUnitCss, .QuantityCss
        {
            width: 80px;
        }
        
        .TotalInRowCss, .GrandTotalCss
        {
            font-family: Tahoma, Arial, MS Sans Serif;
            font-size: small;
            font-weight: bold;
        }
        .GrandTotalCss
        {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <script language="javascript" type="text/javascript"></script>
    <form id="form1" runat="server">
    <div style="margin: auto auto;">
        <asp:GridView ID="GridView1" runat="server" Width="100%" BackColor="White" BorderColor="#DEDFDE"
            BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" AutoGenerateColumns="False"
            BorderStyle="None" ShowFooter="true" ShowHeader="true">
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:TemplateField HeaderText="ID" ItemStyle-Width="100" ItemStyle-HorizontalAlign="Right">
                    <ItemTemplate>
                        <asp:Label ID="LabelID" runat="server" Text='<%# Eval("ID") %>' CssClass='<%# Convert.ToBoolean(Eval("Status"))?"EnabledLabel":"DisbledLabel" %>'></asp:Label>
                    </ItemTemplate>
                    <ItemStyle Width="100px"></ItemStyle>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="NAME">
                    <ItemTemplate>
                        <asp:Label ID="LabelName" runat="server" Text='<%# Eval("Name") %>' CssClass='<%# Convert.ToBoolean(Eval("Status"))?"EnabledLabel":"DisbledLabel" %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <b>Total</b>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="@Price" ItemStyle-Width="200" ItemStyle-HorizontalAlign="Right">
                    <ItemTemplate>
                        <asp:TextBox CssClass="PricePerUnitCss" ID="TextBoxPricePerUnit" runat="server" Text='<%# Eval("PricePerUnit") %>'
                            Enabled='<%# Eval("Status") %>'></asp:TextBox>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Right" Width="200px"></ItemStyle>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Quantity" ItemStyle-Width="200" ItemStyle-HorizontalAlign="Right">
                    <ItemTemplate>
                        <asp:TextBox CssClass="QuantityCss" ID="TextBoxQuantity" runat="server" Enabled='<%# Eval("Status") %>'></asp:TextBox>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Right" Width="200px"></ItemStyle>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Total" ItemStyle-Width="200" ItemStyle-HorizontalAlign="Right">
                    <ItemTemplate>
                        <asp:Label ID="LabelTotalPrice" CssClass="TotalInRowCss" runat="server" Text=''></asp:Label>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Right" Width="200px"></ItemStyle>
                    <FooterTemplate>
                        <asp:Label ID="LabelGrandTotal" CssClass="GrandTotalCss" runat="server" Text=''></asp:Label>
                    </FooterTemplate>
                    <FooterStyle HorizontalAlign="Right" />
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Button ID="Button1" runat="server" Text="Edit" CommandName="Edit" CommandArgument='<%# Eval("ID") %>'
                            Enabled='<%# Eval("Status") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#CCCC99" />
            <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
            <RowStyle BackColor="#F7F7DE" />
            <SelectedRowStyle BackColor="#CE5D5A" ForeColor="White" Font-Bold="True" />
            <SortedAscendingCellStyle BackColor="#FBFBF2" />
            <SortedAscendingHeaderStyle BackColor="#848384" />
            <SortedDescendingCellStyle BackColor="#EAEAD3" />
            <SortedDescendingHeaderStyle BackColor="#575357" />
        </asp:GridView>
        <hr />
    </div>
    
    </form>
</body>
</html>


Code (C#)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Pages_StandDardControl_Grid_GridViewBasic : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        InitClientScript();

        if (!IsPostBack)
        {
            Session["PG_DATASOURCE"] = null;
            GridView1.DataSource = InitDataSource();
            GridView1.DataBind();
        }
    }

    private List<SimpleItem> InitDataSource()
    {
        if (Session["PG_DATASOURCE"] == null)
        {
            List<SimpleItem> myList = new List<SimpleItem>();
            int i = 01;
            myList.Add(new SimpleItem(i++, "มะข่า", 31, true));
            myList.Add(new SimpleItem(i++, "มะขิ่น", 9.25, false));
            myList.Add(new SimpleItem(i++, "มะขบ", 101, false));
            myList.Add(new SimpleItem(i++, "มะงั่ว", 12.50, true));
            myList.Add(new SimpleItem(i++, "มะฝรั่น", 20, true));

            Session["PG_DATASOURCE"] = myList;
        }
        return Session["PG_DATASOURCE"] as List<SimpleItem>;
    }

    protected void Page_Init(object sender, EventArgs e)  // Init(object sender, EventArgs e) 
    {
        GridView1.RowDataBound += new GridViewRowEventHandler(this.OnRowDataBound);

    }

    private void InitClientScript()
    {
        this.CountRow = 0;

        System.Text.StringBuilder scriptBuilder = new System.Text.StringBuilder();
        scriptBuilder.AppendLine();
        scriptBuilder.AppendLine("        var refPricePerUnitCSS = 'PricePerUnitCss'; ");
        scriptBuilder.AppendLine("        var refQuantityCSS = 'QuantityCss'; ");
        scriptBuilder.AppendLine("        var refTotalInRowCSS = 'TotalInRowCss'; ");
        scriptBuilder.AppendLine("        var refGrandTotalCSS = 'GrandTotalCss'; ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("        $(function () { ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("            var totalElement = $('.' + refPricePerUnitCSS).length; ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("            $('.' + refPricePerUnitCSS + ', .' + refQuantityCSS).live('keyup', function () { ");
        scriptBuilder.AppendLine("                // get current id for assume valid index  ");
        scriptBuilder.AppendLine("                var controlName = $(this).attr('id'); ");
        scriptBuilder.AppendLine("                // ASP.NET compose control name with separator _.  ");
        scriptBuilder.AppendLine("                // In template field it's use this pattern >> [PLACEHOLDER_]GRIDVIEWNAME_CONTROLNAME_INDEX ");
        scriptBuilder.AppendLine("                // We need last element for get valid index. ");
        scriptBuilder.AppendLine("                var controlNameArr = controlName.split('_'); ");
        scriptBuilder.AppendLine("                var controlndex = parseInt(controlNameArr[controlNameArr.length - 1], 10); ");
        scriptBuilder.AppendLine("                var capQuantity = FloatTryParse($('.' + refQuantityCSS).eq(controlndex).val()); ");
        scriptBuilder.AppendLine("                var capPricePerUnit = FloatTryParse($('.' + refPricePerUnitCSS).eq(controlndex).val()); ");
        scriptBuilder.AppendLine("                var rowAmount = capPricePerUnit * capQuantity; ");
        scriptBuilder.AppendLine("                var rowAmountStr = Convert2CurrencyFormat(rowAmount); ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("                $('.' + refTotalInRowCSS).eq(controlndex).html(rowAmountStr); ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("                var newColor = 'Tomato'; ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("                if (rowAmount > 0) newColor = 'green'; ");
        scriptBuilder.AppendLine("                else if (rowAmount == 0) newColor = 'gray'; ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("                $('.' + refTotalInRowCSS).eq(controlndex).css('color', newColor); ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("                //Grand total ");
        scriptBuilder.AppendLine("                var grandTotal = 0; ");
        scriptBuilder.AppendLine("                for (var i = 0; i < totalElement; i++) { ");
        scriptBuilder.AppendLine("                    capQuantity = FloatTryParse($('.' + refQuantityCSS).eq(i).val()); ");
        scriptBuilder.AppendLine("                    apPricePerUnit = FloatTryParse($('.' + refPricePerUnitCSS).eq(i).val()); ");
        scriptBuilder.AppendLine("                    grandTotal = grandTotal + (capQuantity * apPricePerUnit); ");
        scriptBuilder.AppendLine("                } ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("                newColor = 'Tomato'; ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("                if (grandTotal > 0) newColor = 'green'; ");
        scriptBuilder.AppendLine("                else if (grandTotal == 0) newColor = 'gray'; ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("                $('.' + refGrandTotalCSS).eq(0).css('color', newColor); ");
        scriptBuilder.AppendLine("                $('.' + refGrandTotalCSS).eq(0).html(Convert2CurrencyFormat(grandTotal)); ");
        scriptBuilder.AppendLine("            }); ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("        }); ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("        function Convert2CurrencyFormat(varData) { ");
        scriptBuilder.AppendLine("            var temp = FloatTryParse(varData); ");
        scriptBuilder.AppendLine("            temp = temp.toFixed(2); ");
        scriptBuilder.AppendLine("            return addCommas(temp); ");
        scriptBuilder.AppendLine("        } ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("        function FloatTryParse(varData) { ");
        scriptBuilder.AppendLine("            var retValue = 0.0; ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("            var temp = varData.toString().replace(\",\", \"\"); ");
        scriptBuilder.AppendLine("            try { ");
        scriptBuilder.AppendLine("                retValue = parseFloat(temp); ");
        scriptBuilder.AppendLine("                if (isNaN(retValue)) retValue = 0; ");
        scriptBuilder.AppendLine("            } ");
        scriptBuilder.AppendLine("            catch (err) { } ");
        scriptBuilder.AppendLine("            return retValue; ");
        scriptBuilder.AppendLine("        } ");
        scriptBuilder.AppendLine(" ");
        scriptBuilder.AppendLine("        // snippet code come from http://www.mredkj.com/javascript/numberFormat.html ");
        scriptBuilder.AppendLine("        function addCommas(nStr) { ");
        scriptBuilder.AppendLine("            nStr += ''; ");
        scriptBuilder.AppendLine("            x = nStr.split('.'); ");
        scriptBuilder.AppendLine("            x1 = x[0]; ");
        scriptBuilder.AppendLine("            x2 = x.length > 1 ? '.' + x[1] : ''; ");
        scriptBuilder.AppendLine("            var rgx = /(\\d+)(\\d{3})/; ");
        scriptBuilder.AppendLine("            while (rgx.test(x1)) { ");
        scriptBuilder.AppendLine("                x1 = x1.replace(rgx, '$1' + ',' + '$2'); ");
        scriptBuilder.AppendLine("            } ");
        scriptBuilder.AppendLine("            return x1 + x2; ");
        scriptBuilder.AppendLine("        } ");

        scriptBuilder.AppendLine();

        System.Web.UI.HtmlControls.HtmlGenericControl ScriptParser
            = new System.Web.UI.HtmlControls.HtmlGenericControl("script");

        ScriptParser.Attributes.Add("type", "text/javascript");
        ScriptParser.Attributes.Add("language", "javascript");
        ScriptParser.InnerHtml = scriptBuilder.ToString();

        this.Header.Controls.Add(ScriptParser);

    }

    private int CountRow
    {
        get
        {
            if (Session["VS_COUNT_ROW"] == null)
                Session["VS_COUNT_ROW"] = 0;
            return Convert.ToInt32(Session["VS_COUNT_ROW"]);
        }
        set { Session["VS_COUNT_ROW"] = value; }
    }

    protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
        }
    }
}

public class SimpleItem
{
    public int ID { get; set; }
    public string Name { get; set; }
    public double PricePerUnit { get; set; }
    public bool Status { get; set; }

    public SimpleItem(int varID, string varName, double varPricePerUnit, bool varStatus)
    {
        this.ID = varID;
        this.Name = varName;
        this.PricePerUnit = varPricePerUnit;
        this.Status = varStatus;
    }

}



งานลักษณะนี้เคยเขียนด้วย javascript มาแล้วค่ะ แต่ใน version นั้น
จะใช้ event RowDataBound เข้ามาช่วยซึ่ง code จะมีลักษณะพันกันค่อนข้างมาก
มีทั้งส่วน server-side และ client-side ที่ทำงานประสานกัน แยกจากกันไม่ได้
เลยเกิดความคิดว่าถ้าเขียนด้วย jQuery มันจะให้ผลดีกว่ามั้ย
โดยต้องการให้ code แยกเป็นอิสระจากกันให้มากที่สุด (ถ้าปรับปรุงจะกระชับกว่าปัจจุบันเยอะค่ะ)
ซึ่งเป็นที่มาของบทความนี้ค่ะ

แนวคิดก้อคือ จับตัว textbox ที่วางไว้ใน template column ของ gridview มา handle event ด้วย jQuery
ซึ่ง event ที่เลือกใช้คือ keyup เพราะลักษณะการคำนวนแบบนี้จะต้องมีการปรับปรุงทุกครั้งที่ีการ เปลี่ยนแปลงข้อมูล
และเพื่อให้ครอบคลุมใน ทุก textbox ใน column ของ gridview จึงกำหนด CSS ให้ textbox เป็นการเฉพาะ
และแยก CSS เพื่อแยกกลุ่มของ control เป็นชุดๆ คือชุดของ PricePerUnit (ราคาต่อหน่วย) ,Quantity(จำนวน)
,sub-total(ราคารวม) และ grand total (ราคารวมทั้งหมด)

ในการระบุว่า user กำลัง คีย์ข้อมูลอยู่ที่ control ตัวใด เนื่องจากเป็น control ใน template column
asp.net จะทำการสร้าง ชุด control ซ้ำๆตามจำนวนแถวและมีการเปลี่ยนชื่อของ control โดย
มี pattern ดังนี้ [PLACEHOLDER_]GRIDVIEWNAME_CONTROLNAME_INDEX
ซึงเมื่อเรากำหนด CSS แบบแยกชุด เราจะระบุกลุ่มทั้งหมดของ control นั้นๆได้ผ่านทาง jQuery selector
และหากตัดค่า index ออกจากชื่อของ control เราก้อจะระบุ ตัว control ปัจจุบันได้
(ซึ่ง ลำดับของ index ที่ asp.net สร้างจะเรียงลำดับเช่นเดียวกับใน array control ของ jQuery)

จากนั้นก็ดึงค่าแลัวนำมาคำนวน และอัพเดตและมีการจัด numeric format ให้เรียบร้อย
คงจะอธิบายการทำงานเพียงเท่านี้ค่ะ

ปล. ที่เขียน jQuery จาก code behide เพราะเป็นวิธีแก้ปัญหาอีกกรณี ถ้าเราแยกกันพัฒนา
ส่วนออกแบบกับ code แยกจากกันค่ะ ในกรณีนี้งานออกแบบจะไม่กระทบอะไรเลยสามารถนำไปแก้
แล้วนำมาประกอบใหม่ได้ตลอดเวลา ส่วน code ก้อเช่นกันค่ะ


บทความอื่น ๆ ที่เกี่ยวข้อง
Go to : jQuery Tutorial : สอน jQuery เขียน jQuery กับ JavaScript เรียน jQuery ในประเทศไทย







   
Share
Bookmark.   

  By : Stupid.gurl.th
  Article : บทความเป็นการเขียนโดยสมาชิก หากมีปัญหาเรื่องลิขสิทธิ์ กรุณาแจ้งให้ทาง webmaster ทราบด้วยครับ
  Score Rating :
  Create Date : 2011-02-17
  Download : No files
Sponsored Links
ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 01
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่