Click here to Skip to main content
15,908,274 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
I use gridview in my webpage to do calculation then I add checkbox in datatable but the main problem is I don't have any error when I debug but my calculation in table didn't work. Before I added checkbox the calculation works perfectly. How to fix it?

What I have tried:

This is javascript calculation from source [^]

JavaScript
<pre> <script type="text/javascript">  

        function CalculateTotals() {
            var gv = document.getElementById("<%= GridView1.ClientID %>");
            var tb = gv.getElementsByTagName("input");
            var lb = gv.getElementsByTagName("span");
            var sub = 0;
            var total = 0;
            var indexQ = 1;
            var indexP = 0;
            var price = 0;
            for (var i = 0; i < tb.length; i++) {
                if (tb[i].type == "text") {
                    ValidateNumber(tb[i]);

                    price = lb[indexP].innerHTML.replace
                        ("$", "").replace(",", "");
                    sub = parseFloat(price) * parseFloat(tb[i].value);
                    if (isNaN(sub)) {
                        lb[i + indexQ].innerHTML = "0.00";
                        sub = 0;
                    }
                    else {
                        lb[i + indexQ].innerHTML =
                            FormatToMoney(sub, "$", ",", "."); 
                    }
                    indexQ++;
                    indexP = indexP + 2;
                    total += parseFloat(sub);
                }
            }
            lb[lb.length - 1].innerHTML =
                FormatToMoney(total, "$", ",", ".");   
        }
        function ValidateNumber(o) {
            if (o.value.length > 0) {
                o.value = o.value.replace(/[^\d]+/g, ''); //allow only whole numbers  
            }
        }
        function isThousands(position) {
            if (Math.floor(position / 3) * 3 == position) return true;
            return false;
        };
        function FormatToMoney(theNumber, theCurrency, theThousands, theDecimal) {
            var theDecimalDigits = theNumber.toFixed(2).split('.')[1];
            theNumber = "" + Math.floor(theNumber);
            var theOutput = theCurrency;
            for (x = 0; x < theNumber.length; x++) {
                theOutput += theNumber.substring(x, x + 1);
                if (isThousands(theNumber.length - x - 1) && (theNumber.length - x - 1 != 0)) {
                    theOutput += theThousands;
                };
            };
            theOutput += theDecimal + theDecimalDigits;
            return theOutput;
        }
    </script>

ASP.NET
<pre><form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
                <Columns>                  
                     <asp:TemplateField  HeaderText="No">
            <ItemTemplate>
                <asp:CheckBox ID="ChkBox" runat="server"/>
            </ItemTemplate>
        </asp:TemplateField> 
                    <asp:BoundField DataField="Item" HeaderText="Item" />
                    <asp:BoundField DataField="Number" HeaderText="Number" />
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                    <asp:TemplateField HeaderText="Quantity">
                        <ItemTemplate>
                            <asp:TextBox ID="TXTQty" runat="server" onkeyup="CalculateTotals();"></asp:TextBox>
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:Label ID="LBLQtyTotal" runat="server" Font-Bold="true" ForeColor="Blue" Text="" ></asp:Label>
                             Total Amount:
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Price">
                        <ItemTemplate>
                            <asp:Label ID="LBLPrice" runat="server" Text='<%# Eval("Price","{0:C}") %>'></asp:Label>
                        </ItemTemplate>
                        <FooterTemplate>
                            Total Qty:
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Total">
                        <ItemTemplate>
                            <asp:Label ID="LBLSubTotal" runat="server" ForeColor="White" Text="0.00"></asp:Label>
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:Label ID="LBLTotal" runat="server" ForeColor="white" Font-Bold="true" Text="0.00"></asp:Label>
                        </FooterTemplate> 
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>   
        </div>
    </form>

This is code behind
C#
private void BindQuotationDataToGrid()
        {
            DataTable dt = new DataTable();
            DataRow dr = null;

            dt.Columns.Add(new DataColumn("No"));
            dt.Columns.Add(new DataColumn("Item", typeof(int)));
            dt.Columns.Add(new DataColumn("Number", typeof(string)));
            dt.Columns.Add(new DataColumn("Name", typeof(string)));
            dt.Columns.Add(new DataColumn("Price", typeof(string)));

            dr = dt.NewRow();
            dr["Item"] = 1;
            dr["Number"] = "485-3A";
            dr["Name"] = "Light ring";         
            dr["Price"] = "16.52";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["Item"] = 2;
            dr["Number"] = "985-BB";
            dr["Name"] = "Charger";
            dr["Price"] = "5.37";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["Item"] = 3;
            dr["Number"] = "658-C2";
            dr["Name"] = "Lens";
            dr["Price"] = "4.21";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["Item"] = 4;
            dr["Number"] = "AA-1536";
            dr["Name"] = "Shirt";
            dr["Price"] = "14.35";
            dt.Rows.Add(dr);
            //Bind the GridView  
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                BindQuotationDataToGrid();
        }
    }

I've made 7 columns which is No, Item, Part Name, Quantity, Price and Total. For  No column I added checkbox using <asp:TemplateField>, Quantity I made textbox for user to enter the quantity of product, Price is where it show price using label same goes to Total I used  label where it will show the amount once user enter the quantity. Before I added checkbox my calculation going well. But after add the checkbox it doesn't work properly

For instance, I made testing by enter 4 product which is has 4 rows for 4 product. When I entered the quantity for first product, it show the answer of calculation in second row at price column. It supposed to be in Total column at first row. When I enter quantity for second product it doesn't show anything at total column but the price changed for showing price of product to display the amount of total for first row. For the third row is the column price still show the price doesnt change anything when I enter the quantity but for total column it display the total for first row and the fourth column doesn't changed anything either price or total column even though I've entered the quantity

What I expect for output is when user check the checkbox and enter the quantity it will make the calculation and show at total column row by row. Then it will show the product that has been checked by user under the datatable(which is I still haven't make it yet)
Posted
Updated 27-Feb-23 16:46pm
v12
Comments
Richard Deeming 22-Feb-23 10:06am    
"Didn't work" tells us precisely nothing. You need to provide a clear and complete description of the problem, including the full details of any errors, and samples of your input, your expected output, and your actual output.
kimkyie 22-Feb-23 20:32pm    
I has explain the problem I'm facing on the question right now. I hope you understand it and can help me

1 solution

Take a look at this article here on CodeProject: How To: Do Calculations in GridView[^] or this one: Calculate ASP.Net GridView Running and Grand Total using JavaScript[^]. I found these using this search: asp.net webform gridview calculated column - Google Search[^].

My suggestion to you is to start with a small/minimal sample/mock-up and get the process working. Then do a separate page with a larger test. This will make working on the solution more agile/quicker and far easier to read and work on. It is what I do and would have to do if I was to work on your problem. Once you are happy that the solution is working, update your main project.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900