简体   繁体   English

添加 3 个标签控件的值以在另一个标签控件中输出结果时出错

[英]Error with adding values of 3 label controls to output result in another label control

Here is the full description of what I am trying to achieve.这是我想要实现的目标的完整描述。

The way I designed it is that I have我设计它的方式是我有

  • 3 Checkboxes 3 复选框
  • 3 DropDown controls: Quantity 3 下拉控件:数量
  • 7 Label controls: 3 Labels for Unit Price, 3 Labels for SubTotal and one Label for GrandTotal 7 个标签控件:3 个单价标签、3 个小计标签和一个 GrandTotal 标签

On page load, DropDown will be disabled, Unit Price Labels will have values as "100", "200" and "100" respectively and the 3 SubTotal Labels will have initial values as "0", and GrandTotal Label will be "0".在页面加载时,DropDown 将被禁用,单价标签的值分别为“100”、“200”和“100”,3 个小计标签的初始值为“0”,GrandTotal 标签将为“0” .

When a user clicks on any of the Checkboxes, the DropDown attached to that clicked Checkbox will be enabled and when user selects quantity from DropDown, the value of Unit Price Label will be multiplied by the value in the quantity DropDown and output the result in SubTotal Labels.当用户单击任何一个复选框时,将启用附加到该单击复选框的下拉列表,当用户从下拉列表中选择数量时,单价标签的值将乘以数量下拉列表中的值,并在 SubTotal 中输出结果标签。

Finally, all the values of SubTotal Labels will be added and the result will be displayed in the GrandTotal Label.最后,将SubTotal Labels 的所有值相加,结果将显示在GrandTotal Label 中。

This is how the view will look like这是视图的样子

Product        Unit Price       Quantity     SubTotal      GrandTotal

Product1          100              3            300

Product2          200              1            200

Product3          100              2            200          
                                                               700

Here is my CODE (forgive the way I display my code. I tried to upload my code but it did not enter the code window, since I'm using mobile device to ask this question)这是我的代码(请原谅我显示代码的方式。我尝试上传我的代码但它没有进入代码窗口,因为我正在使用移动设备提出这个问题)

protected void Page_Load(object sender, EventArgs e)
{
    unitprice1.Text = ("100").ToString();
    unitprice2.Text = ("200").ToString();
    unitprice3.Text = ("100").ToString();
}

protected void CheckBox1_CheckedChanged(object sender, EventArgs e) 
{
    Product1DropDown.Enabled = CheckBox1.Checked;
    Subtotal1.Text = ("0").ToString();
}

protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
    Product2DropDown.Enabled = CheckBox2.Checked;
    Subtotal2.Text = ("0").ToString();
}

protected void CheckBox3_CheckedChanged(object sender, EventArgs e)
{
    Product3DropDown.Enabled = CheckBox3.Checked;
    Subtotal3.Text = ("0").ToString();
}

protected void Product1DropDown_SelectedIndexChanged(object sender, EventArgs e)
{
    if (Product1DropDown.SelectedIndex > 0)
    {
        Qty1.Text = Product1DropDown.SelectedItem.Text;
        Subtotal1.Text = Convert.ToString(Convert.ToInt32(Qty1.Text) * Convert.ToInt32(unitprice1.Text)).ToString();
    }
}

protected void Product2DropDown_SelectedIndexChanged(object sender, EventArgs e)
{
    if (Product2DropDown.SelectedIndex > 0)
    {
        Qty2.Text = Product2DropDown.SelectedItem.Text;
        Subtotal2.Text = Convert.ToString(Convert.ToInt32(Qty2.Text) * Convert.ToInt32(unitprice2.Text)).ToString();
    }
}

protected void Product3DropDown_SelectedIndexChanged(object sender, EventArgs e)
{
    if(Product3DropDown.SelectedIndex > 0)
    {
        Qty3.Text = Product3DropDown.SelectedItem.Text;Subtotal3.Text = Convert.ToString(Convert.ToInt32(Qty3.Text) * Convert.ToInt32(unitprice3.Text)).ToString();
    }
}    

Ensure that you've included AutoPostBack="true" for each CheckBox :确保您已为每个CheckBox包含AutoPostBack="true"

<asp:CheckBox ID="checkBox1" runat="server" Checked="false" OnCheckedChanged="checkBox1_CheckedChanged" AutoPostBack="true" />

and also for each DropDownList :以及每个DropDownList

<asp:DropDownList id="product1DropDown" runat="server" OnSelectedIndexChanged="product1DropDown_SelectedIndexChanged" AutoPostBack="true" Enabled="false" style="align-content:center;width: 75px" />

Create a method to calculate the subtotal.创建一个方法来计算小计。 Since we have to calculate subtotals for 3 different products, we'll create a method.由于我们必须计算 3 种不同产品的小计,因此我们将创建一个方法。 The parameters will be the quantity from the DropDownList, and the unit price from the label.参数将是 DropDownList 中的数量和标签中的单价。

private decimal CalculateSubtotal(string strQty, string strUnitPrice)
{
    int qty = 0;
    decimal unitPrice = 0m;
    decimal subtotal = 0m;

    //clear msg
    lblMsg.Text = string.Empty;

    if (!String.IsNullOrEmpty(strQty))
    {
        //try to convert
        Int32.TryParse(strQty, out qty);
    }
    else
    {
        throw new Exception("Error: Qty is null or empty");
    }

    if (!String.IsNullOrEmpty(strUnitPrice))
    {
        //try to convert
        Decimal.TryParse(strUnitPrice, out unitPrice);

        //calculate
        subtotal = qty * unitPrice;
    }
    else
    {
        throw new Exception("Error: UnitPrice is null or empty");
    }
    
    return subtotal;
}

 

Next, create a method to calculate the grand total.接下来,创建一个计算总计的方法。 This method will call CalculateSubtotal for each of the products.此方法将为每个产品调用CalculateSubtotal

CalculateGrandTotal计算GrandTotal

private void CalculateGrandTotal()
{
    decimal subtotal1 = 0m; //use 'm' for decimal
    decimal subtotal2 = 0m; //use 'm' for decimal
    decimal subtotal3 = 0m; //use 'm' for decimal

    //calculate subtotal1 - only calculate if CheckBox is enabled
    if (checkBox1.Enabled && !String.IsNullOrEmpty(product1DropDown.Text))
    {
        //calculate subtotal
        subtotal1 = CalculateSubtotal(product1DropDown.Text, lblProduct1UnitPrice.Text);
    }

    //set value
    lblProduct1Subtotal.Text = subtotal1.ToString("$###,##0.00");

    //calculate subtotal 2 - only calculate if CheckBox is enabled
    if (checkBox2.Enabled && !String.IsNullOrEmpty(product2DropDown.Text))
    {
        //calculate subtotal
        subtotal2 = CalculateSubtotal(product2DropDown.Text, lblProduct2UnitPrice.Text);
    }

    //set value
    lblProduct2Subtotal.Text = subtotal2.ToString("$###,##0.00");

    //calculate subtotal3 - only calculate if CheckBox is enabled
    if (checkBox3.Enabled && !String.IsNullOrEmpty(product3DropDown.Text))
    {
        //calculate subtotal
        subtotal3 = CalculateSubtotal(product3DropDown.Text, lblProduct3UnitPrice.Text);
    }

    //set value
    lblProduct3Subtotal.Text = subtotal3.ToString("$###,##0.00");

    //calculate
    decimal grandTotal = subtotal1 + subtotal2 + subtotal3;

    //set value
    lblGrandTotal.Text = grandTotal.ToString("$###,##0.00");
}

In each of the CheckBox CheckChanged event handlers, not only do we need to determine whether or not to enable the drop down, but also re-calculate the grand total.在每个 CheckBox CheckChanged事件处理程序中,我们不仅需要判断是否启用下拉,还需要重新计算总计。 I've also decided to reset the quantity and subtotal to 0 if the checkbox is disabled.如果复选框被禁用,我还决定将数量和小计重置为 0。

ex :例如

protected void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    ////uncomment for debugging
    //lblMsg.Text = "Info: checkBox1.Checked: " + checkBox1.Checked.ToString();
    //System.Diagnostics.Debug.WriteLine("Info: checkBox1.Checked: " + checkBox1.Checked.ToString());

    //set value
    product1DropDown.Enabled = checkBox1.Checked;

    if (!product1DropDown.Enabled)
    {
        //not enabled - reset values
        product1DropDown.Text = string.Empty;
        lblProduct1Subtotal.Text = "$0.00";
    }

    //calculate
    CalculateGrandTotal();
}

Since, we need to re-calculate the grand total each time a quantity is changed, as well as, the subtotal for that particular product, we just call CalculateGrandTotal();由于每次更改数量时都需要重新计算总计以及该特定产品的小计,因此我们只需调用CalculateGrandTotal(); . .

ex :例如

protected void product1DropDown_SelectedIndexChanged(object sender, EventArgs e)
{
    CalculateGrandTotal();
}

Here's the complete solution-it's been tested:这是完整的解决方案 - 它已经过测试:

VS 2019 : VS 2019

Create a new ASP.NET Web Application (.NET Framework)创建新的ASP.NET Web 应用程序 (.NET Framework)

  • Project Name: BMICalc项目名称: BMICalc
  • Click Create点击创建
  • Click Empty点击清空
  • Click Create点击创建

Add Web Form添加网页表单

  • In VS menu, click Project在 VS 菜单中,单击项目
  • Select Web Form (name: default.aspx)选择Web 表单(名称:default.aspx)

default.aspx :默认.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="TestAspNetDU._default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">

        <div style="top: 10px; left: 150px; position: absolute;">

            <asp:Table ID="tbl1" BorderStyle="none" Border="0px" CellPadding="2" CellSpacing="0" runat="server" Width="410">
                <asp:TableHeaderRow ID="tbl1HeaderRow">
                    <asp:TableHeaderCell ID="tbl1CheckBoxHeading" Text="" style="text-align:center" />
                    <asp:TableHeaderCell ID="tbl1ProductHeading" Text="Product" style="text-align:center" />
                    <asp:TableHeaderCell ID="tbl1UnitPriceHeading" Text="Unit Price" style="text-align:center" />
                    <asp:TableHeaderCell ID="tbl1QuantityHeading" Text="Quantity" style="text-align:center" />
                    <asp:TableHeaderCell ID="tbl1SubtotalHeading" Text="Subtotal" style="text-align:center" />
                </asp:TableHeaderRow>
                
                <asp:TableRow ID="tbl1Row1">
                    <asp:TableCell Width="35px" style="align-content:center;text-align:center;vertical-align:middle">
                        <asp:CheckBox ID="checkBox1" runat="server" Checked="false" OnCheckedChanged="checkBox1_CheckedChanged" AutoPostBack="true" />
                    </asp:TableCell>

                    <asp:TableCell Width="100px" style="text-align:left">
                        <asp:Label id="lblProduct1Name" runat="server" Text="Product1" style="text-align:left" />
                    </asp:TableCell>

                    <asp:TableCell Width="75px" style="align-content:center;text-align:center">
                        <asp:Label id="lblProduct1UnitPrice" runat="server" Text="100" />
                    </asp:TableCell>

                    <asp:TableCell Width="100px" style="align-content:center;text-align:center">
                        <asp:DropDownList id="product1DropDown" runat="server" OnSelectedIndexChanged="product1DropDown_SelectedIndexChanged" AutoPostBack="true" Enabled="false" style="align-content:center;width: 75px" />
                    </asp:TableCell>

                    <asp:TableCell Width="100px" style="text-align:right">
                        <asp:Label id="lblProduct1Subtotal" runat="server" Text="0.00" />
                    </asp:TableCell>
                </asp:TableRow>

               
                <asp:TableRow ID="tbl1Row2">
                    <asp:TableCell Width="35px" style="align-content:center;text-align:center;vertical-align:middle">
                        <asp:CheckBox ID="checkBox2" runat="server" Checked="false" OnCheckedChanged="checkBox2_CheckedChanged" AutoPostBack="true" />
                    </asp:TableCell>

                    <asp:TableCell Width="100px" style="text-align:left">
                        <asp:Label id="lblProduct2Name" runat="server" Text="Product2" style="text-align:left" />
                    </asp:TableCell>

                    <asp:TableCell Width="75px" style="align-content:center;text-align:center">
                        <asp:Label id="lblProduct2UnitPrice" runat="server" Text="200" style="text-align:center" />
                    </asp:TableCell>

                    <asp:TableCell Width="100" style="align-content:center;text-align:center">
                        <asp:DropDownList id="product2DropDown" runat="server" OnSelectedIndexChanged="product2DropDown_SelectedIndexChanged" AutoPostBack="true" Enabled="false" style="align-content:center;width: 75px" />
                    </asp:TableCell>

                    <asp:TableCell Width="100px" style="text-align:right">
                        <asp:Label id="lblProduct2Subtotal" runat="server" Text="0.00" />
                    </asp:TableCell>
                </asp:TableRow>

               
                <asp:TableRow ID="tbl1Row3">
                    <asp:TableCell Width="35px" style="align-content:center;text-align:center;vertical-align:middle">
                        <asp:CheckBox ID="checkBox3" runat="server" Checked="false" OnCheckedChanged="checkBox3_CheckedChanged" AutoPostBack="true" />
                    </asp:TableCell>

                    <asp:TableCell Width="100px" style="text-align:left">
                        <asp:Label id="lblProduct3Name" runat="server" Text="Product3" style="text-align:left" />
                    </asp:TableCell>

                    <asp:TableCell Width="75px" style="align-content:center;text-align:center">
                        <asp:Label id="lblProduct3UnitPrice" runat="server" Text="100" style="text-align:center" />
                    </asp:TableCell>

                    <asp:TableCell Width="100" style="align-content:center;text-align:center">
                        <asp:DropDownList id="product3DropDown" runat="server" OnSelectedIndexChanged="product3DropDown_SelectedIndexChanged" AutoPostBack="true" Enabled="false" style="align-content:center;width: 75px" />
                    </asp:TableCell>

                    <asp:TableCell Width="100px" style="text-align:right">
                        <asp:Label id="lblProduct3Subtotal" runat="server" Text="0.00" />
                    </asp:TableCell>
                </asp:TableRow>
            </asp:Table>
        </div>

        <div style="top: 120px; left: 150px; position: absolute">
            <asp:Table ID="tbl1GrandTotal" BorderStyle="none" Border="0px" CellPadding="0" CellSpacing="0" runat="server" Width="410">
                <asp:TableRow ID="tbl1GrandTotalRow">
                    <asp:TableCell Width="160px" style="align-content:center;text-align:center;vertical-align:middle"></asp:TableCell>

                    <asp:TableCell Width="125px" style="font-weight:bold; text-align:center">
                        <asp:Label id="lblGrandTotalHeading" runat="server" Text="Grand Total:" />
                    </asp:TableCell>

                    <asp:TableCell Width="100px" style="font-weight:bold; text-align:right">
                        <asp:Label id="lblGrandTotal" runat="server" Text="0.00" />
                    </asp:TableCell>
                </asp:TableRow>
            </asp:Table>
        </div>

        <div style="top: 625px; left: 150px; position: absolute">
            <span style="color:red">
                <asp:Label ID="lblMsg" runat="server" Text="" />
            </span>
        </div>
    </form>
</body>
</html>

default.aspx.cs默认.aspx.cs

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

namespace TestAspNetDU
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //set values
          
            lblProduct1UnitPrice.Text = "100";
            lblProduct2UnitPrice.Text = "200";
            lblProduct3UnitPrice.Text = "100";

            //populate DropDownList
            for(int i = 0; i < 100; i++)
            {
                if (i > 0)
                {
                    //add
             
                    product1DropDown.Items.Add(i.ToString());
                    product2DropDown.Items.Add(i.ToString());
                    product3DropDown.Items.Add(i.ToString());
                }
                else
                {
                    //add - for 0, show empty (blank)
                    product1DropDown.Items.Add("");
                    product2DropDown.Items.Add("");
                    product3DropDown.Items.Add("");
                }
            }
        }

        private void CalculateGrandTotal()
        {
            decimal subtotal1 = 0m; //use 'm' for decimal
            decimal subtotal2 = 0m; //use 'm' for decimal
            decimal subtotal3 = 0m; //use 'm' for decimal

            try
            {
                //calculate subtotal1 - only calculate if CheckBox is enabled
                if (checkBox1.Enabled && !String.IsNullOrEmpty(product1DropDown.Text))
                {
                    //calculate subtotal
                    subtotal1 = CalculateSubtotal(product1DropDown.Text, lblProduct1UnitPrice.Text);
                }

                //set value
                lblProduct1Subtotal.Text = subtotal1.ToString("$###,##0.00");
            }
            catch(Exception ex)
            {
                //ToDo: log msg

                //set value
                lblMsg.Text = "Error (CalculateGrandTotal 1) - " + ex.Message;

                //uncommenting the following line may be useful for debugging
                //throw ex;
            }

            try
            {
                //calculate subtotal 2 - only calculate if CheckBox is enabled
                if (checkBox2.Enabled && !String.IsNullOrEmpty(product2DropDown.Text))
                {
                    //calculate subtotal
                    subtotal2 = CalculateSubtotal(product2DropDown.Text, lblProduct2UnitPrice.Text);
                }

                //set value
                lblProduct2Subtotal.Text = subtotal2.ToString("$###,##0.00");
            }
            catch(Exception ex)
            {
                //ToDo: log msg

                //set value
                lblMsg.Text = "Error (CalculateGrandTotal 2) - " + ex.Message;

                //uncommenting the following line may be useful for debugging
                //throw ex;
            }

            try
            {
                //calculate subtotal3 - only calculate if CheckBox is enabled
                if (checkBox3.Enabled && !String.IsNullOrEmpty(product3DropDown.Text))
                {
                    //calculate subtotal
                    subtotal3 = CalculateSubtotal(product3DropDown.Text, lblProduct3UnitPrice.Text);
                }

                //set value
                lblProduct3Subtotal.Text = subtotal3.ToString("$###,##0.00");
            }
            catch(Exception ex)
            {
                //ToDo: log msg

                //set value
                lblMsg.Text = "Error (product3DropDown_SelectedIndexChanged) - " + ex.Message;

                //uncommenting the following line may be useful for debugging
                //throw ex;
            }

            //calculate
            decimal grandTotal = subtotal1 + subtotal2 + subtotal3;

            //set value
            lblGrandTotal.Text = grandTotal.ToString("$###,##0.00");
        }

        private decimal CalculateSubtotal(string strQty, string strUnitPrice)
        {
            int qty = 0;
            decimal unitPrice = 0m;
            decimal subtotal = 0m;

            //clear msg
            lblMsg.Text = string.Empty;

            if (!String.IsNullOrEmpty(strQty))
            {
                //try to convert
                Int32.TryParse(strQty, out qty);
            }
            else
            {
                throw new Exception("Error: Qty is null or empty");
            }

            if (!String.IsNullOrEmpty(strUnitPrice))
            {
                //try to convert
                Decimal.TryParse(strUnitPrice, out unitPrice);

                //calculate
                subtotal = qty * unitPrice;
            }
            else
            {
                throw new Exception("Error: UnitPrice is null or empty");
            }
            
            return subtotal;
        }

        protected void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            ////uncomment for debugging
            //lblMsg.Text = "Info: checkBox1.Checked: " + checkBox1.Checked.ToString();
            //System.Diagnostics.Debug.WriteLine("Info: checkBox1.Checked: " + checkBox1.Checked.ToString());

            //set value
            product1DropDown.Enabled = checkBox1.Checked;

            if (!product1DropDown.Enabled)
            {
                //not enabled - reset values
                product1DropDown.Text = string.Empty;
                lblProduct1Subtotal.Text = "$0.00";
            }

            //calculate
            CalculateGrandTotal();
        }

        protected void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            //uncomment for debugging
            //lblMsg.Text = "Info: checkBox2.Checked: " + checkBox2.Checked.ToString();

            //set value
            product2DropDown.Enabled = checkBox2.Checked;

            if (!product2DropDown.Enabled)
            {
                //not enabled - reset values
                product2DropDown.Text = string.Empty;
                lblProduct2Subtotal.Text = "$0.00";
            }

            //calculate
            CalculateGrandTotal();
        }

        protected void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            //uncomment for debugging
            //lblMsg.Text = "Info: checkBox3.Checked: " + checkBox3.Checked.ToString();

            //set value
            product3DropDown.Enabled = checkBox3.Checked;

            if (!product3DropDown.Enabled)
            {
                //not enabled - reset values
                product3DropDown.Text = string.Empty;
                lblProduct3Subtotal.Text = "$0.00";
            }

            //calculate
            CalculateGrandTotal();
        }

        protected void product1DropDown_SelectedIndexChanged(object sender, EventArgs e)
        {
            CalculateGrandTotal();
        }

        protected void product2DropDown_SelectedIndexChanged(object sender, EventArgs e)
        {
            CalculateGrandTotal();
        }

        protected void product3DropDown_SelectedIndexChanged(object sender, EventArgs e)
        {
            CalculateGrandTotal();
        }
    }
}

在此处输入图片说明

Resources :资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM