如何使用foreach循环在不显示“ 0”的情况下显示数组的内容?

问题描述 投票:-1回答:1
     public partial class frmEnhancedInvoiceTotal : Form
{
    public frmEnhancedInvoiceTotal()
    {
        InitializeComponent();
    }

    private void BtnExit_Click(object sender, EventArgs e)
    {
        Close();
    }
    decimal[] decTotalofInvoicesArray = new decimal[5];
    int intNumberOfInvoices = 0; //global variables 
    decimal decTotalOfInvoicesVariable = 0m;
    decimal decAverageOfInvoices = 0m;


    private void BtnCalculate_Click(object sender, EventArgs e)
    {
        //Convert = Class, .ToDecimal = method,
        //when the user clicks the calulate button,
        //we collect the subtotal, determine the appropriate discount,
        //calculate the total and output the result to the screen. 
        //***EARN PARTIAL CREDIT PUT COMMENTS***

        //Input

        try
        {
            decimal decSubtotal = 0m; //initialize subtotal with a value of zero. We'll collect from the user later.
            if (Decimal.TryParse(txtSubtotal.Text,
                System.Globalization.NumberStyles.Currency, //now can type a $ sign and now break the code 
                System.Globalization.CultureInfo.CurrentCulture,
                out decSubtotal))  //.tryparse attempts to convert but is a fail safe
                                   //parse does 2 things - does something and tells you if works 

                decTotalofInvoicesArray[intNumberOfInvoices] = decSubtotal;

            {
                //Processing
                decimal decDiscountPercent = 0m; //defining a new variable (discount percent) allow for real #, giving it a intial value of 0. Decimal variables you have to add m

                if (decSubtotal >= 500m) //if my subtotal is 500 or more
                {
                    decDiscountPercent = 0.2m; //inside braces is what will happen to the question above 
                                               //set discount rate to 20%
                }
                else if (decSubtotal < 500m && decSubtotal >= 250m) //if subtotal is between 250 & 500
                                                                    //^^redundant because < 500 is already stated in the first if statement 
                                                                    //could just right else if(decSubtotal >=250m)
                {
                    decDiscountPercent = 0.15m; //set discount rate to 15%
                }


                else if (decSubtotal < 250m && decSubtotal >= 100m) //if subtotal is between 100 and 250
                {
                    decDiscountPercent = 0.1m; //set discount to 10%
                }


                //if subtotal is less than 100, dicounter percent is 0%

                decimal decDiscountAmount = decDiscountPercent * decSubtotal;
                decimal decTotal = decSubtotal - decDiscountAmount; //He is going so fast




                //Aggregate Processing - across mutliple clicks of the calculate button

                //old way of doing it = intNumberOfInvoices = intNumberOfInvoices + 1;
                intNumberOfInvoices++; //value of variable plus one

                //old way of doing it decTotalOfInvoices = decTotalOfInvoices + decTotal;
                decimal decSum = 0m;
                for (int intColIndex = 0; intColIndex < decTotalofInvoicesArray.Length; intColIndex++)
                {
                    decSum += decTotalofInvoicesArray[intColIndex];
                }
                decTotalOfInvoicesVariable = decSum;
                decAverageOfInvoices = decSum / decTotalofInvoicesArray.Length;



                //Output 
                txtSubtotal.Text = decSubtotal.ToString("c");
                txtDiscountPercent.Text = decDiscountPercent.ToString("p2"); //sending a numeric value and sending it to text = gives error 
                txtDiscountAmount.Text = decDiscountAmount.ToString("c");    //dot ToString makes value a text value and sends to textbox in form
                                                                             //c=currency    //"p2" - 2 = how many decimal places 
                                                                             //P = percentage 
                txtTotal.Text = decTotal.ToString("c");



                //aggregate output
                txtNumberOfInvoices.Text = intNumberOfInvoices.ToString();
                txtTotalOfInvoices.Text = decTotalOfInvoicesVariable.ToString("c");
                txtAverageOfInvoices.Text = decAverageOfInvoices.ToString("c");

                //breakpoint analysis = click on the grey side bar and slowly work through the code to find the error. Essentially pause the code and run the code one point at a time  
            }

        }

         catch (FormatException) //you do not know what went wrong in the try part. It just errors anyways because SOMETHING went wrong 
        {
            MessageBox.Show("Please enter valid numeric values.", "Entry Error");
        }
        catch (OverflowException) //something is to big 
        {
            MessageBox.Show("Please try smaller numbers", "Entry Error");
        }
        catch //generic error code because why not 
        {
            MessageBox.Show("An unexpected error has occured. Please try again.", "Entry Error");
        }

    }

    private void BtnClearTotals_Click(object sender, EventArgs e)
    {
        //When resetting aggregate/global info - need to reset the variables AND the visual interface
        intNumberOfInvoices = 0;
        decTotalOfInvoicesVariable = 0m;
        decAverageOfInvoices = 0m;

        //  txtNumberOfInvoices.Text = ""; //setting the variable to nothing. Erase the information in the text box 
        txtNumberOfInvoices.Clear();
        txtTotalOfInvoices.Clear();
        txtAverageOfInvoices.Clear();
    }

    private void TxtSubtotal_TextChanged(object sender, EventArgs e)
    {
        txtDiscountPercent.Clear();
        txtDiscountAmount.Clear();
        txtTotal.Clear();
    }

    private void BtnDisplayTotals_Click(object sender, EventArgs e)
    {
        String strOrderTotals = "";
        //for (int intColIndex = 0; intColIndex < intNumberOfInvoices; intColIndex++)
        //{
        //    strOrderTotals += decTotalofInvoicesArray[intColIndex] + "\n";
        //}


        foreach (decimal decTotalInvoices in decTotalofInvoicesArray)
        {
            if (strOrderTotals == "0")
            {
                strOrderTotals += decTotalInvoices + "\n";
            }
        }
        MessageBox.Show(strOrderTotals.ToString());
    }

    private bool IsValidData()
    {
        return
            IsPresent(txtSubtotal) && //did you type anyting
            IsDecimal(txtSubtotal) && //make sure you types a real number
            IsWithinRange(txtSubtotal, 0m, 1000m); //is the number in the range
    }

    private bool IsPresent(TextBox textBox) //send an entire textbox into method
    {
        if (textBox.Text == "")
        {
            MessageBox.Show(textBox.Tag.ToString() + " is a required field.", "Missing Entry"); //textbox is whatever is in the (TextBox textBox)
            textBox.Focus();
            return false;
        }
        return true;
    }

    private bool IsDecimal(TextBox textBox)
    {
        decimal decTestValue = 0m;
        if (!Decimal.TryParse(textBox.Text, out decTestValue)) //! - dont succusfully tryparse
        {
            MessageBox.Show(textBox.Tag.ToString() + " must be a numeric value", "Entry Error"); //textbox is whatever is in the (TextBox textBox)
            textBox.Focus();
            return false;
        }
        return true;
    }

    private bool IsInteger(TextBox textBox)
    {
        int intTestValue = 0;
        if (!Int32.TryParse(textBox.Text, out intTestValue)) //! - dont succusfully tryparse
        {
            MessageBox.Show(textBox.Tag.ToString() + " must be a whole number.", "Missing Entry"); //textbox is whatever is in the (TextBox textBox)
            textBox.Focus();
            return false;
        }
        return true;
    }

    private bool IsWithinRange(TextBox textBox, decimal decMin, decimal decMax)
    {
        decimal decTestValue = Convert.ToDecimal(textBox.Text);
        if (decTestValue < decMin || decTestValue > decMax) //to small or to big
        {
            MessageBox.Show(textBox.Tag.ToString() + " must be between " + decMin.ToString() + " and " + decMax.ToString() + "." + "Out of Range"); //textbox is whatever is in the (TextBox textBox)
            textBox.Focus();
            return false;
        }
        return true;
    }
}

}

基本上,我有一个发票总额窗口表格,用户输入小计值,然后根据折扣百分比计算总值。在分配中,据说要创建一个最多包含五个发票总额的数组。我的问题是,当我键入2个小计的值并且单击显示总计时,我键入的2个数字与3个零一起显示。我想知道如何使用foreach循环仅显示我输入的数字而不显示零。

c#
1个回答
0
投票

看来您没有在foreach中添加任何内容。

foreach (decimal decTotalInvoices in decTotalofInvoicesArray)
{
    if (strOrderTotals == "0")
    {
        strOrderTotals += decTotalInvoices + "\n";
    }
}
MessageBox.Show(strOrderTotals.ToString());

我是否正确阅读您想显示每张发票的信息,您也想要总额吗?带有for循环的这段代码应该可以工作。我

        strOrderTotals = "My Invoices\n";
        decimal decOrderTotals = 0;
        for (int i = 0; i < decTotalofInvoicesArray.Length; i++)
        {
            if (decTotalofInvoicesArray[i] != 0)
            {
                strOrderTotals += "Invoice : " + decTotalofInvoicesArray[i] + "\n";
                decOrderTotals += decTotalofInvoicesArray[i];
            }
        }
        strOrderTotals += "Total of invoices: " + decOrderTotals;
        MessageBox.Show(strOrderTotals.ToString());
© www.soinside.com 2019 - 2024. All rights reserved.