简体   繁体   中英

How to calculate a total from list boxes in a form

How would I get my program to calculate a total from 2 different list boxes I have in my form. I have tried many different things and I would get random values that I don't understand where they come from. The goal of this is that the user selects what cookie type they want and the amount they want. At the bottom of the form, there is a label that calculates the total. But when I have tried creating the code for this I would get numbers that don't make sense like 0, 2, 4 and etc.

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

        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {
            const int ESTIMATED_ARRIVAL = 3;
            label10.Text = monthCalendar1.SelectionStart.AddDays(ESTIMATED_ARRIVAL).ToShortDateString();
        }

        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }

Here is my code. I have looked all over the internet for any kind of remote solution and I have found nothing that has helped me. I have been working on this for hours on end.

This is what my form looks like. 在此处输入图像描述

Without seeing your code, it's a little hard to answer specifically, but here's one way to do it.

First, we realize that we need to bundle a "Description" along with a "Quantity" or "Price" for each item in our list boxes. One easy way to do this is to create a basic class:

public class MyItem
{
    public string Description { get; set; }
    public decimal Value { get; set; }

    public MyItem(string description, decimal value)
    {
        Description = description;
        Value = value;
    }
}

Now we can create lists of this class and use these lists as data sources for our list boxes, so that each Item in a listbox is really an instance of the MyItem class:

private void Form1_Load(object sender, EventArgs e)
{
    // Set the DataSource for each listbox to 
    // a list of our custom "MyItem" class
    lstCookieTypes.DataSource = new List<MyItem>
    {
        new MyItem("$1.50 - Chocolate Chip Cookie", 1.5m),
        new MyItem("$1.00 - Oatmeal Cookie", 1),
        new MyItem("$1.25 - Sugar Cookie", 1.25m),
    };

    lstCookieQuantities.DataSource = new List<MyItem>
    {
        new MyItem("1 Cookie", 1),
        new MyItem("1 Dozen Cookies", 12),
        new MyItem("2 Dozen Cookies", 24),
    };

    // Continued below...

Now that we have our list boxes populated with data, we need to specify the DisplayMember , or the property that we want it to use for displaying text to the user. This will be our "Description" property:

    // Use the "Description" property of "MyItem" as the DisplayMember
    lstCookieTypes.DisplayMember = "Description";
    lstCookieQuantities.DisplayMember = "Description";
}

Next we need a method that can take the selected item from each listbox, determine the value for those items, multiply them together, and display the result (as currency) to the user. Note that we have to cast the SelectedValue to MyItem in order to access the Value property (and there's some null coalescing going on to handle cases where SelectedValue is null ):

private void DisplayTotal()
{
    // Calculate the total by multiplying the "Value" for the selected 
    // cookie type with the "Value" for the selected cookie quantity
    var total = ((lstCookieTypes.SelectedValue as MyItem)?.Value ?? 0)  *
                ((lstCookieQuantities.SelectedValue as MyItem)?.Value ?? 0);

    lblPrice.Text = total.ToString("C");  // "C" will format the number as currency
}

Finally, all that's left is to call this method from the SelectedIndexChanged event for each listbox, so our total gets updated when the user selects a new cookie or a new quantity:

private void lstCookieTypes_SelectedIndexChanged(object sender, EventArgs e)
{
    DisplayTotal();
}

private void lstCookieQuantities_SelectedIndexChanged(object sender, EventArgs e)
{
    DisplayTotal();
}

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