简体   繁体   中英

Getting the sum of numbers in a listbox?

Screenshot of the Form First time poster, and im in need of some help here. I am working on a program that calculates an athletes salary after hiring agents, lawyers, agents, etc. I have a listbox that displays the salary*the constant percentage of the agent. I CANNOT seem to get the sum of the numbers entered so i can subtract them from the total salary and display it in a label. I would love some help, very new to C#.

The area in question is commented out under the Switch

public partial class athleteForm : Form
{
    public athleteForm()
    {
        InitializeComponent();
    }

    const decimal LAWYER_PERCENT = 0.10m;
    const decimal AGENT_PERCENT = 0.05m;
    const decimal PA_PERCENT = 0.03m;
    const decimal TRAINER_PERCENT = 0.07m;
    const string LAWYER_STRING = "Lawyer";
    const string AGENT_STRING = "Agent";
    const string PA_STRING = "Personal Assistant";
    const string TRAINER_STRING = "Trainer";
    string profFirstName;
    string profLastName;
    string profSelect;
    decimal profPay;


    public void athleteForm_Load(object sender, EventArgs e)
    {


    }

    public void profAddButton_Click(object sender, EventArgs e)
    {
        decimal startingSalary = Convert.ToDecimal(startingSalaryText.Text);
        profFirstName = profFirstNameText.Text;
        profLastName = profLastNameText.Text;
        profSelect = profComboBox.GetItemText(profComboBox.SelectedItem);
        decimal lawyerPay = startingSalary * LAWYER_PERCENT;
        decimal agentPay = startingSalary * AGENT_PERCENT;
        decimal trainerPay = startingSalary * TRAINER_PERCENT;
        decimal paPay = startingSalary * PA_PERCENT;



        switch (profComboBox.GetItemText(profComboBox.SelectedItem))
        {
            case "Lawyer":
                profPay = lawyerPay;
                break;

            case "Agent":
                profPay = agentPay;
                break;

            case "Trainer":
                profPay = trainerPay;
                break;

            case "Personal Assistant":
                profPay = paPay;
                break;


        }

        profListBox.Items.Add(profFirstName + "     " + profLastName + "     " + profSelect);
        profPayList.Items.Add("$ " +  profPay);

        //decimal sumOfListbox =
        // (from string S in profPayList.Items
        // select Convert.ToDecimal(S))
        // .Sum();

        decimal sum =
     profPayList.Items
             .Cast<string>()
             .Sum(v =>
             {
                 decimal d;
                 return decimal.TryParse(v, out d) ? d : 0m;
             });



        remainSalaryLabel.Text = (sum.ToString());
    }

    public void clearButton_Click(object sender, EventArgs e)
    {

        switch (MessageBox.Show("Are you sure you want to clear all professionals?",
          "WonderWord",
          MessageBoxButtons.YesNoCancel,
          MessageBoxIcon.Question))
        {
            case DialogResult.Yes:
                profListBox.Items.Clear();
                profPayList.Items.Clear();
                remainSalaryLabel.Text = " ";
                break;

            case DialogResult.No:
                // "No" processing
                break;

            case DialogResult.Cancel:
                // "Cancel" processing
                break;

        }




    }

}

}

The problem is that you are storing your data as a string prefixed with a dollar sign ($). eg "$5";

When your are calculating the sum of all of your data, you are correctly using a decimal.TryParse to convert the string to a decimal. However, in this case, the TryParse will not succeed in extracting the number due to the dollar sign.

Therefore, your options for fix this are:

  1. Remove the dollar sign before parsing;
  2. Use the Decimal.TryParse overload that handles numberstyles and currency symbols;
  3. Maintain a separate list of numbers to sum instead of storing them within the ListBox so you don't have to deal with the dollar sign. If you wish to still display the numbers, you can still bind the list of numbers to the ListBox and update whenever a new number is added.

Option 2 would be your best option for the current state of your code. Assuming you're dealing with US culture, your code will need to look similar to this:

NumberStyles style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US"); 

 decimal sum = profPayList.Items
         .Cast<string>()
         .Sum(v =>
         {
             decimal d;
             return decimal.TryParse(v, style, culture, out d) ? d : 0m;
         });

Option 3 is what I would be going with if you have time to rewrite what you have as it will solve some other potentially issues with your code that could arise in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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