Kiviuq
Kiviuq

Reputation: 45

How do I assign values to items in the list box in c#?

I have a List Box with different Cakes in them. How do I give each cake a price and have my label display the total cost of the selected cakes? The following is the code I have so far.

for (int index = 0; index < lstCakes.SelectedItems.Count; index++)
        {
            strCakes += Environment.NewLine + lstCakes.SelectedItems[index].ToString();
        }

double tax = 1.13;
        lblOrdered.Text = "You have ordered: " + strCakes + '\n' + "Total Cost: " + (tax * cakeCost).ToString("C");

I tried using switch like the following but that only shows the cost of the last selected item.

switch (lstCakes.SelectedIndex)
        {
            case 0:
                if (lstCakes.SelectedIndex == 0)
                {
                    cakeCost = 18;
                }
                break;
            case 1:
                if (lstCakes.SelectedIndex == 1)
                {
                    cakeCost = 25;
                }
                break;
            case 2:
                if (lstCakes.SelectedIndex == 2)
                {
                    cakeCost = 40;
                }
                break;
            case 3:
                if (lstCakes.SelectedIndex == 3)
                {
                    cakeCost = 30;
                }
                break;
        }

Any suggestion are appreciated.

Upvotes: 0

Views: 2190

Answers (2)

Levi Botelho
Levi Botelho

Reputation: 25204

Assuming that this is a desktop application, you will probably want to put your prices in a config file so that they can be changed later. You add an <appSettings> block to your App.config file with an entry for each cake and then use the ConfigurationManager.AppSettings[] command to retrieve them.

So if this is a Windows Forms app, then on the form load you can go into your app settings, retrieve the details for all the cakes that you want and then populate your list box with entries for each one (see http://msdn.microsoft.com/en-us/library/z38x31c0.aspx). This way you can dynamically create the text for each entry. If you want each line to contain the price you are going to have to hardcode it into the line's text. (I think that is what you are asking...)

One final note. You shouldn't use + to concatenate strings. Strings in C# are immutable -- that means that the string itself cannot be modified (the reason why is a whole other topic that I can explain if you wish). In order to concatenate two strings with "+", C# needs to create a third string and fill it with the contents of the first two, and this drains performance. To concatenate strings more efficiently, use either a StringBuilder object and the Append() method, or use String.Format() which works the same way.


Immutable strings:

Strings at their core are arrays of characters. Just as you cannot resize an array, you cannot resize a string. This is because arrays are stored on the stack... the stack is a piece of memory which is filled with instructions to run your program that are all "stacked" on top of each other. Stack memory is pre-allocated and for all intents and purposes you cannot dynamically change the memory footprint of objects on the stack. You can have an array of 10 ints containing 5 ints and 5 empty spaces, but you cannot take an int[5] and change it to an int[10]. If you want to add 5 more ints to an int[5] you need to instantiate a new int[10] and fill it up. The same thing goes for a string.

The solution to the array resizing problem is dealt with using Lists and their derivatives. They function using heap memory. This is similar to how a StringBuilder object functions. If you want to know more about stack and heap memory and how it affects how your program runs, this might help you understand a bit better http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx. It is really important to know, because it can explain a lot of mysteries that will stump beginner programmers. Good for you for asking.

Upvotes: 1

Prabhu Murthy
Prabhu Murthy

Reputation: 9261

The cake prices could be maintained on a Enum

enum CakePrices{
ChocCake = 20,
VanillaCake = 50
}

Calculate the Cost:

int TotalCost;
for (int index = 0; index < lstCakes.SelectedItems.Count; index++)
{
  strCakes += Environment.NewLine + lstCakes.SelectedItems[index].ToString();

  //The name of the List Items should match the names on the enum,for this to work
  TotalCost += (int)Enum.Parse(typeof(CakePrices),
                               lstCakes.SelectedItems[index].ToString() ,
                               false)
}

Console.WriteLine("You have ordered:" + strCakes + '\n' + "Total Cost: " + TotalCost);

Upvotes: 0

Related Questions