Click here to Skip to main content
15,891,993 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello! I have to create a Windows From so a user can choose from one of these ComboBoxes (Beverages, Appetizers, Main Course, Dessert) to add an item to a restaurant table bill. As each item is selected in the ComboBoxes, add the price of that item to the bill. The user can click the Clear Bill Button to restore the Subtotal:, Tax: and Total: fields to $0.00.. I'm stuck on how to return each item and its price from the comboBox for calculation.

What I have tried:

public partial class Form1 : Form
  {

      public struct MenuOrders
      {
          public static string item;
          public static double price;
      }

      double subtotal = 0;
      double tax = .03;
      double taxes;
      double total = 0;
     MenuOrders itemOrder = new MenuOrders();


      private void getValue()
      {

          itemOrder.price = Convert.ToDouble(itemOrder);
          outputBox1.Items.Add("Price: " + itemOrder.price);
          Bill();

      }


      private void Bill()
      {
          subtotal += itemOrder.price;
          total += itemOrder.price + (itemOrder.price * tax);
          taxes += itemOrder.price * tax;
          outputBox1.Items.Add("Subtotal: " + subtotal.ToString("C2"));
          outputBox1.Items.Add("Tax: " + taxes.ToString("C2"));
          outputBox1.Items.Add("Total: " + total.ToString("C2"));
      }

      private void changingDropdown(object sender, EventArgs e)
          {
          if (sender == beverageComboBox)
              getValue(beverageComboBox.SelectedItem.ToString());
          else if (sender == appetizerComboBox)
              getValue(appetizerComboBox.SelectedItem.ToString());
          else if (sender == MainecourseComboBox)
              getValue(MaincourseComboBox.SelectedItem.ToString());
          else getValue(dessertComboBox.SelectedItem.ToString());

      }
Posted
Updated 31-Mar-17 19:27pm
v2
Comments
Richard MacCutchan 29-Mar-17 3:48am    
I would suggest using ListBoxes rather than Combos, unless you expect the user to add new products to the combos. When a selection changes you just get the product name and price, copy them to the bill and add the price to the running total. You could make your code much simpler by using the same event handler for each list, since the handler does not need to know anything about the list items beyond name and price.
F-ES Sitecore 29-Mar-17 4:11am    
Give your controls proper names to make it obvious what they relate to. You might know now that textBox2 is "tax" but will you remember in the future? What about someone else reading your code? Call it "textBoxTax" to "txtTax" or something like that.
Prifti Constantine 29-Mar-17 4:40am    
Why are you storing the ComboBox.SelectedItem inside the string variable cb when you never use that string?
OfficialSub0 31-Mar-17 22:33pm    
Thank you for your replies. I updated the code and tried to get rid of anything unnecessary. The syntax errors I'm receiving now is "Form1.MenuOrders.price cannot be accessed with an instance reference; qualify with a type name instead" so I used "MenuOrders" as the type but this led to no avail. The other syntax error was "no overload for getValue takes 1 method"? This is probably any easy fix but I'm lost

1 solution

Here you go... A quick hack...
C#
using System;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

namespace WFRestaurantBill
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            for (int i = 0; i < 10; i++)
            {
                lbBeverage.Items.Add(new MenuItem { Name = $"Beverage {i}", Price = (decimal)(i * 3.33) });
                lbAppetizer.Items.Add(new MenuItem { Name = $"Appetizer {i}", Price = (decimal)(i * 1.11) });
                lbMainCourse.Items.Add(new MenuItem { Name = $"MainCourse {i}", Price = (decimal)(i * 5.55) });
                lbDessert.Items.Add(new MenuItem { Name = $"Dessert {i}", Price = (decimal)(i * 4.44) });
            }

            BillItems = new BindingList<BillItem>();
            lbBill.DataSource = BillItems;
            lbBill.DataBindings.DefaultDataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged;
            UpdateBillTotal();
        }

        private void OnSelectedMenuItemChanged(object sender, EventArgs e)
        {
            var selectedItem = (MenuItem)((ListBox)sender).SelectedItem;
            var selectedName = selectedItem.Name;
            var item = BillItems.Where(x => x.MenuItem.Name == selectedName).FirstOrDefault();

            if (item == null)
            {
                item = new BillItem { Quantity = 1, MenuItem = selectedItem };
                BillItems.Add(item);
            }
            else
            {
                item.Quantity++;
                typeof(ListBox).InvokeMember("RefreshItems",
                  BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod,
                  null, lbBill, new object[] { });
            }
            BillTotal += item.MenuItem.Price;
            UpdateBillTotal();
        }

        public BindingList<BillItem> BillItems { get; set; }
        public decimal BillTotal { get; set; }

        private void OnResetBillClick(object sender, EventArgs e)
        {
            BillTotal = 0;
            BillItems.Clear();
            UpdateBillTotal();
        }

        private void UpdateBillTotal()
        {
            tbTotal.Text = $"{BillTotal:N2}";
        }
    }

    public class MenuItem
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
    }

    public class BillItem
    {
        public int Quantity { get; set; }
        public MenuItem MenuItem { get; set; }
        public decimal Total => Quantity * MenuItem.Price;
        public override string ToString() 
            => $"{Quantity.ToString("N0").PadLeft(3)} {MenuItem.Name.PadRight(15)}{Total.ToString("N2").PadLeft(6)}";
    }
}

To see how this works in more detail, here is the auto-generated Form Designer code:
C#
namespace WFRestaurantBill
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.lbBeverage = new System.Windows.Forms.ListBox();
            this.lbAppetizer = new System.Windows.Forms.ListBox();
            this.lbMainCourse = new System.Windows.Forms.ListBox();
            this.lbDessert = new System.Windows.Forms.ListBox();
            this.lbBill = new System.Windows.Forms.ListBox();
            this.tbTotal = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.butClear = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // lbBeverage
            // 
            this.lbBeverage.DisplayMember = "Name";
            this.lbBeverage.FormattingEnabled = true;
            this.lbBeverage.Location = new System.Drawing.Point(12, 12);
            this.lbBeverage.Name = "lbBeverage";
            this.lbBeverage.Size = new System.Drawing.Size(120, 95);
            this.lbBeverage.TabIndex = 0;
            this.lbBeverage.SelectedValueChanged += new System.EventHandler(this.OnSelectedMenuItemChanged);
            // 
            // lbAppetizer
            // 
            this.lbAppetizer.DisplayMember = "Name";
            this.lbAppetizer.FormattingEnabled = true;
            this.lbAppetizer.Location = new System.Drawing.Point(12, 113);
            this.lbAppetizer.Name = "lbAppetizer";
            this.lbAppetizer.Size = new System.Drawing.Size(120, 95);
            this.lbAppetizer.TabIndex = 0;
            this.lbAppetizer.SelectedValueChanged += new System.EventHandler(this.OnSelectedMenuItemChanged);
            // 
            // lbMainCourse
            // 
            this.lbMainCourse.DisplayMember = "Name";
            this.lbMainCourse.FormattingEnabled = true;
            this.lbMainCourse.Location = new System.Drawing.Point(12, 214);
            this.lbMainCourse.Name = "lbMainCourse";
            this.lbMainCourse.Size = new System.Drawing.Size(120, 95);
            this.lbMainCourse.TabIndex = 0;
            this.lbMainCourse.SelectedValueChanged += new System.EventHandler(this.OnSelectedMenuItemChanged);
            // 
            // lbDessert
            // 
            this.lbDessert.DisplayMember = "Name";
            this.lbDessert.FormattingEnabled = true;
            this.lbDessert.Location = new System.Drawing.Point(12, 315);
            this.lbDessert.Name = "lbDessert";
            this.lbDessert.Size = new System.Drawing.Size(120, 95);
            this.lbDessert.TabIndex = 0;
            this.lbDessert.SelectedValueChanged += new System.EventHandler(this.OnSelectedMenuItemChanged);
            // 
            // lbBill
            // 
            this.lbBill.FormattingEnabled = true;
            this.lbBill.Location = new System.Drawing.Point(152, 12);
            this.lbBill.Name = "lbBill";
            this.lbBill.Size = new System.Drawing.Size(120, 290);
            this.lbBill.TabIndex = 0;
            // 
            // tbTotal
            // 
            this.tbTotal.Location = new System.Drawing.Point(152, 337);
            this.tbTotal.Name = "tbTotal";
            this.tbTotal.ReadOnly = true;
            this.tbTotal.Size = new System.Drawing.Size(120, 20);
            this.tbTotal.TabIndex = 1;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(149, 321);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(45, 13);
            this.label1.TabIndex = 2;
            this.label1.Text = "TOTAL:";
            // 
            // butClear
            // 
            this.butClear.Location = new System.Drawing.Point(152, 387);
            this.butClear.Name = "butClear";
            this.butClear.Size = new System.Drawing.Size(120, 23);
            this.butClear.TabIndex = 3;
            this.butClear.Text = "RESET BILL";
            this.butClear.UseVisualStyleBackColor = true;
            this.butClear.Click += new System.EventHandler(this.OnResetBillClick);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 455);
            this.Controls.Add(this.butClear);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.tbTotal);
            this.Controls.Add(this.lbBill);
            this.Controls.Add(this.lbDessert);
            this.Controls.Add(this.lbMainCourse);
            this.Controls.Add(this.lbAppetizer);
            this.Controls.Add(this.lbBeverage);
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ListBox lbBeverage;
        private System.Windows.Forms.ListBox lbAppetizer;
        private System.Windows.Forms.ListBox lbMainCourse;
        private System.Windows.Forms.ListBox lbDessert;
        private System.Windows.Forms.ListBox lbBill;
        private System.Windows.Forms.TextBox tbTotal;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button butClear;
    }
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900