[ASP.net WebForm] GridView在編輯列中的TextBox輸入數字,計算小計 with jQuery

[ASP.net WebForm] GridView在編輯列中的TextBox輸入數字,計算小計 with jQuery

因為同事需要Sample Code,找了一下網路上是有一堆

FAQ: GridView Calculation with JavaScript

但使用jQuery的方式似乎比較少,由於個人比較喜歡用jQuery取代傳統的Javascript

所以此篇紀錄一下,jQuery的實現方式(另,跟上篇不同的是在EditItemTemplate中用jQuery做計算動作)

先建DB Table


Create table calc
(
  id int identity primary key,
  num1 int,
  num2 int,
  subtotal int

)
Go
Insert into calc values (1,1,NULL),(2,2,NULL)
Go

 

.aspx代碼:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
    <title></title>
    <script src="js/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        //計算該列的小計
        function CalculateTotals(txtClientID1, txtClientID2, txtClientIDsubtotal) {

            var num1 = parseInt($("#" + txtClientID1).attr("value"));
            var num2 = parseInt($("#" + txtClientID2).attr("value"));
            if (isNaN(num1) == false && isNaN(num2) == false) {
                //txt_num1和txt_num2的文字都是數字才要處理
                var subtotal = num1 + num2;//加總小計
                $("#" + txtClientIDsubtotal).attr("value",subtotal);
            }

        
        }
        function updateRow(lnkUpdateUniqueID, txtClientIDsbtotal) {
            if (event.keyCode == 13) {//在小計TextBox按下Enter鍵

                __doPostBack(lnkUpdateUniqueID, '');//做更新寫DB動作
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:NorthwindChineseConnectionString %>" 
        SelectCommand="SELECT [id], [num1], [num2], [subtotal] FROM [calc]" 
        UpdateCommand="UPDATE [calc] SET [num1] = @num1, [num2] = @num2, [subtotal] = @subtotal WHERE [id] = @id">
        <UpdateParameters>
            <asp:Parameter Name="num1" Type="Int32" />
            <asp:Parameter Name="num2" Type="Int32" />
            <asp:Parameter Name="subtotal" Type="Int32" />
            <asp:Parameter Name="id" Type="Int32" />
        </UpdateParameters>
    </asp:SqlDataSource>
    <br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="id" DataSourceID="SqlDataSource1" 
        onrowdatabound="GridView1_RowDataBound">
        <Columns>
            <asp:TemplateField ShowHeader="False">
                <EditItemTemplate>
                    <asp:LinkButton ID="lnk_Update" runat="server" CausesValidation="True" 
                        CommandName="Update" Text="更新"></asp:LinkButton>
                    &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" 
                        CommandName="Cancel" Text="取消"></asp:LinkButton>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" 
                        CommandName="Edit" Text="編輯"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" 
                ReadOnly="True" SortExpression="id" />
            <asp:TemplateField HeaderText="num1" SortExpression="num1">
                <EditItemTemplate>
                    <asp:TextBox ID="txt_num1" runat="server" Text='<%# Bind("num1") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("num1") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="num2" SortExpression="num2">
                <EditItemTemplate>
                    <asp:TextBox ID="txt_num2" runat="server" Text='<%# Bind("num2") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("num2") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="subtotal" SortExpression="subtotal">
                <EditItemTemplate>
                    <asp:TextBox ID="txt_subtotal" runat="server" Text='<%# Bind("subtotal") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("subtotal") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>


    </form>
</body>
</html>

Code-Behind代碼:

 


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

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

    }


    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType==DataControlRowType.DataRow)
        {
           TextBox txt_num1 = (TextBox)e.Row.FindControl("txt_num1");
           TextBox txt_num2 = (TextBox)e.Row.FindControl("txt_num2");
           TextBox txt_subtotal = (TextBox)e.Row.FindControl("txt_subtotal");
           //預設一開始的RowDataBound是在Select Command下觸發
           //但因為要使用jQuery計算的動作在EditItemTemplate,所以抓出來的控制項要防呆
           if (txt_num1 != null && txt_num2!=null && txt_subtotal!=null)
           {
               string js = @"CalculateTotals('"+txt_num1.ClientID+"','"+txt_num2.ClientID+"','"+txt_subtotal.ClientID+"'); ";
               txt_num1.Attributes["onkeyup"] = js;
               txt_num2.Attributes["onkeyup"] = js;
                
           }
         
           LinkButton lnk_Update = (LinkButton)e.Row.FindControl("lnk_Update");
           if (lnk_Update != null && txt_subtotal != null)
           {
               string js = @"updateRow('"+lnk_Update.UniqueID+"','"+txt_subtotal.ClientID+"')";
               txt_subtotal.Attributes["onkeydown"] = js;
           }
        }
    }
}

執行結果:

一開始

image

滑鼠點擊「編輯」

image

在num1或num2隨便敲數字的話

image

若鍵盤focus在subtotal上按下Enter鍵的話

image

會更新至DB

image

 

※此範例在firefox下,若在subtotal按下Enter鍵是沒反應的

Demo包下載