I am trying to calculate the "change" due at the end of my program into a MessageBox. The Dollar amount entered into a text box needs to have the total subtracted from it but I just can't seem to see what I am doing wrong. Can anyone help me finish this?
namespace HardwareStore
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
ProductBox.Items.Add(new Hardware() { ItemNo = 1010, ProdName = "Hammer ", Price = (decimal)14.99d });
ProductBox.Items.Add(new Hardware() { ItemNo = 1056, ProdName = "Bag of Nails ", Price = (decimal)19.99d });
ProductBox.Items.Add(new Hardware() { ItemNo = 2001, ProdName = "Saw ", Price = (decimal)29.99d });
ProductBox.Items.Add(new Hardware() { ItemNo = 2005, ProdName = "Chainsaw ", Price = (decimal)69.99d });
ProductBox.Items.Add(new Hardware() { ItemNo = 3090, ProdName = "Ladder ", Price = (decimal)109.99d });
}
private void frmMain_Load(object sender, EventArgs e)
{
}
private void btnAddItem_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < int.Parse(txtQuantity.Text); i++)
ReceiptBox.Items.Add(ProductBox.Items[ProductBox.SelectedIndex]);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReceiptBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal subTotal = ReceiptBox.Items.Cast<Hardware>().Sum(item => item.Price);
decimal tax = Math.Round((subTotal * .075M), 2);
decimal total = subTotal + tax;
lblSub.Text = "$" + subTotal.ToString();
lblTax.Text = "$" + tax.ToString();
lblTotal.Text = "$" + total.ToString();
lblSub.Visible = true;
lblTax.Visible = true;
lblTotal.Visible = true;
}
private void btnChange_Click(object sender, EventArgs e)
{
MessageBox.Show("Change Due: $ ");
}
}
}
I think I caught it twice...
decimal total = 0; //declare the total as global variable
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal subTotal = ReceiptBox.Items.Cast<Hardware>().Sum(item => item.Price);
decimal tax = Math.Round((subTotal * .075M), 2);
total = subTotal + tax;
lblSub.Text = "$" + subTotal.ToString();
lblTax.Text = "$" + tax.ToString();
lblTotal.Text = "$" + total.ToString();
lblSub.Visible = true;
lblTax.Visible = true;
lblTotal.Visible = true;
}
private void btnChange_Click(object sender, EventArgs e)
{
decimal customerPay = 100;
if (total != 0){
decimal changeDue = customerPay - total;
txtDollar.Txt = "$ " + changeDue.toString();
MessageBox.Show("Change Due: " + txtDollar.Txt);
}
}
Related
it's my first post here. I'm learning C# (visual studio) at the moment and we have been building a program through given tasks. The last task is to create an "undo" button. This is the code so far:
namespace GestBar_v1._0
{
public partial class Form1 : Form
{
string[] bebidas = { "Café", "Ice Tea", "Água", "Aguardente" };
double[] precoBebidas = { 0.8, 1.5, 1.0, 1.0 };
string[] alimentacao = { "Bolos", "Sandes Mistas", "Torrada", "Salgados" };
double[] precoAlimentacao = { 1.0, 1.5, 1.5, 1.0 };
double soma = 0;
double fecho = 0;
void resetTxt()
{
txtPreco.BackColor = Color.White;
txtPreco.ForeColor = Color.Black;
txtPreco.Font = new Font("Microsoft Sans Serif", 11, FontStyle.Regular);
label2.Text = "Preço Final";
}
private void Processo(string[] items, double[] prices, int itemIndex)
{
if (listaProduto.Items.Contains(items[itemIndex]))
{
int index = listaProduto.Items.IndexOf(items[itemIndex]);
double count = double.Parse(listaUnidade.Items[index].ToString());
listaPreco.Items[index] = Math.Round(prices[itemIndex] * (count + 1), 2);
listaUnidade.Items[index] = count + 1;
soma += prices[itemIndex];
}
else
{
listaProduto.Items.Add(items[itemIndex]);
listaPreco.Items.Add(prices[itemIndex]);
listaUnidade.Items.Add(1);
soma += prices[itemIndex];
}
txtPreco.Text = soma.ToString();
}
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
resetTxt();
btn11.Visible = true;
btn12.Visible = true;
btn13.Visible = true;
btn14.Visible = true;
btn11.Text = bebidas[0] + "\n" + precoBebidas[0] + "€";
btn12.Text = bebidas[1] + "\n" + precoBebidas[1] + "€";
btn13.Text = bebidas[2] + "\n" + precoBebidas[2] + "€";
btn14.Text = bebidas[3] + "\n" + precoBebidas[3] + "€";
btn21.Visible = false;
btn22.Visible = false;
btn23.Visible = false;
btn24.Visible = false;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnAliment_Click(object sender, EventArgs e)
{
resetTxt();
btn21.Visible = true;
btn22.Visible = true;
btn23.Visible = true;
btn24.Visible = true;
btn21.Text = alimentacao[0] + "\n" + precoAlimentacao[0] + "€";
btn22.Text = alimentacao[1] + "\n" + precoAlimentacao[1] + "€";
btn23.Text = alimentacao[2] + "\n" + precoAlimentacao[2] + "€";
btn24.Text = alimentacao[3] + "\n" + precoAlimentacao[3] + "€";
btn11.Visible = false;
btn12.Visible = false;
btn13.Visible = false;
btn14.Visible = false;
}
private void btnTodosP_Click(object sender, EventArgs e)
{
resetTxt();
btn11.Visible = true;
btn12.Visible = true;
btn13.Visible = true;
btn14.Visible = true;
btn21.Visible = true;
btn22.Visible = true;
btn23.Visible = true;
btn24.Visible = true;
btn11.Text = bebidas[0] + "\n" + precoBebidas[0] + "€";
btn12.Text = bebidas[1] + "\n" + precoBebidas[1] + "€";
btn13.Text = bebidas[2] + "\n" + precoBebidas[2] + "€";
btn14.Text = bebidas[3] + "\n" + precoBebidas[3] + "€";
btn21.Text = alimentacao[0] + "\n" + precoAlimentacao[0] + "€";
btn22.Text = alimentacao[1] + "\n" + precoAlimentacao[1] + "€";
btn23.Text = alimentacao[2] + "\n" + precoAlimentacao[2] + "€";
btn24.Text = alimentacao[3] + "\n" + precoAlimentacao[3] + "€";
}
private void btn11_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 0);
}
private void btn12_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 1);
}
private void btn13_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 2);
}
private void btn14_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 3);
}
private void btn21_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 0);
}
private void btn22_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 1);
}
private void btn23_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 2);
}
private void btn24_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 3);
}
private void btnNovo_Click(object sender, EventArgs e)
{
resetTxt();
fecho += Convert.ToDouble(txtPreco.Text);
listaProduto.Items.Clear();
listaPreco.Items.Clear();
listaUnidade.Items.Clear();
txtPreco.Clear();
soma = 0;
}
private void btnRetirarSelec_Click(object sender, EventArgs e)
{
if (listaProduto.SelectedIndex >= 0)
{
int index = listaProduto.SelectedIndex;
double count = double.Parse(listaUnidade.Items[index].ToString());
soma -= count * precoBebidas[index];
listaUnidade.Items.RemoveAt(index);
listaPreco.Items.RemoveAt(index);
listaProduto.Items.RemoveAt(index);
txtPreco.Text = soma.ToString();
}
}
private void btnReduzQnt_Click(object sender, EventArgs e)
{
int index = -1;
if (listaProduto.SelectedIndex >= 0)
{
index = listaProduto.SelectedIndex;
}
else if (listaPreco.SelectedIndex >= 0)
{
index = listaPreco.SelectedIndex;
}
else if (listaUnidade.SelectedIndex >= 0)
{
index = listaUnidade.SelectedIndex;
}
if (index >= 0)
{
double count = double.Parse(listaUnidade.Items[index].ToString());
if (count > 1)
{
soma -= precoBebidas[index];
soma -= precoAlimentacao[index];
listaUnidade.Items[index] = count - 1;
listaPreco.Items[index] = Math.Round(precoBebidas[index] * (count - 1), 2);
listaPreco.Items[index] = Math.Round(precoAlimentacao[index] * (count - 1), 2);
txtPreco.Text = soma.ToString();
}
else
{
listaUnidade.Items.RemoveAt(index);
listaPreco.Items.RemoveAt(index);
listaProduto.Items.RemoveAt(index);
txtPreco.Text = soma.ToString();
}
}
}
private void btnFechoC_Click(object sender, EventArgs e)
{
txtPreco.Text = fecho.ToString();
txtPreco.BackColor = Color.Green;
txtPreco.ForeColor = Color.White;
txtPreco.Font = new Font("Microsoft Sans Serif", 11, FontStyle.Bold);
label2.Text = "Saldo Final";
MessageBox.Show("A caixa foi Encerrada.");
fecho = 0;
}
private void btnReturn_Click(object sender, EventArgs e)
{
}
}
}
I'm sorry about some of the Portuguese elements in the code. Can anyone help out on how to do this? I'm completly lost on this one.
I thought of creating an array and making every button click start by saving the "status quo" to the erray and having it update the listboxes through a button. But I couldn't implement it. The fixed numbers on arrays seems to be the factor.
When you say fixed numbers on arrays, do you mean that it is a hindrance that they can only be of pre-defined sizes?
If that's the case, then use a List. First import the necessary library then create the list, both as shown below:
using System.Collections.Generic;
List<type> myList = new List<type>();
You can add as many items to a list without pre-defining its size.
To append items to the list use:
myList.Append(someData);
To then access the last action made by the user (which you have already appended to the list), use:
type lastAction = myList[-1];
Windows forms newbie here, just have a simple question regarding numeric up-down tool.
I have created a program that calculates the cost for car rentals based on size, insurance and discounts. The calculations work fine, however the up-down seems to be "stuck" and shows the values for each day of rental one day behind. For example, if a small size car is $60 per day, and I change the numeric up-down to 2 days, it will show the correct price when 3 days are selected.
Any suggestions on where I've gone wrong would be appreciated.
Code below:
namespace ica3_eventdriven
{
public partial class Form1 : Form
{
const double smallRate = 40.00;
const double midRate = 50.00;
const double sportRate = 60.00;
const double insurance = 15.00;
const double AMA_Discount = 0.1;
int days;
double total;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void tbxName_TextChanged(object sender, EventArgs e)
{
enableControls();
}
private void enableControls()
{
if(tbxName.Text != String.Empty)
{
rbSmall.Enabled = true;
rbMid.Enabled = true;
rbSports.Enabled = true;
cbxInsurance.Enabled = true;
cbxAMA.Enabled = true;
ctrDays.Enabled = true;
}
}
private void rbSmall_CheckedChanged(object sender, EventArgs e)
{
Calculate();
}
private void Calculate()
{
int.TryParse(ctrDays.Text, out days);
if (rbSmall.Checked)
{
total = smallRate * days;
labelTotal.Text = total.ToString("c");
if(cbxInsurance.Checked)
{
total = (smallRate * days) + (insurance * days);
labelTotal.Text = total.ToString("c");
}
if(cbxAMA.Checked)
{
total = 0.9 * (smallRate * days);
labelTotal.Text = total.ToString("c");
}
if(cbxInsurance.Checked && cbxAMA.Checked)
{
total = 0.9 * ((smallRate * days) + (insurance * days));
labelTotal.Text = total.ToString("c");
}
}
if (rbMid.Checked)
{
total = midRate * days;
labelTotal.Text = total.ToString("c");
if (cbxInsurance.Checked)
{
total = (midRate * days) + (insurance * days);
labelTotal.Text = total.ToString("c");
}
if (cbxAMA.Checked)
{
total = 0.9 * (midRate * days);
labelTotal.Text = total.ToString("c");
}
if (cbxInsurance.Checked && cbxAMA.Checked)
{
total = 0.9 * ((midRate * days) + (insurance * days));
labelTotal.Text = total.ToString("c");
}
}
if (rbSports.Checked)
{
total = sportRate * days;
labelTotal.Text = total.ToString("c");
if (cbxInsurance.Checked)
{
total = (sportRate * days) + (insurance * days);
labelTotal.Text = total.ToString("c");
}
if (cbxAMA.Checked)
{
total = 0.9 * (sportRate * days);
labelTotal.Text = total.ToString("c");
}
if (cbxInsurance.Checked && cbxAMA.Checked)
{
total = 0.9 * ((sportRate * days) + (insurance * days));
labelTotal.Text = total.ToString("c");
}
}
}
private void ctrDays_ValueChanged(object sender, EventArgs e)
{
Calculate();
}
private void cbxInsurance_CheckedChanged(object sender, EventArgs e)
{
Calculate();
}
private void cbxAMA_CheckedChanged(object sender, EventArgs e)
{
Calculate();
}
private void rbMid_CheckedChanged(object sender, EventArgs e)
{
Calculate();
}
private void rbSports_CheckedChanged(object sender, EventArgs e)
{
Calculate();
}
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
The program is for a pizza menu, the button I click to add the pizza adds £3.00 on top of the actual total, I have looked for errors but can not find the problem. The program is not fully finished, only the adding of the pizza total is complete but something is wrong with the code which I can not find.
I also would like any suggestion to make the program more efficient.
string stuffedcrust;
string Deeppan;
string thincrispy;
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{ //Add type of crust to summary box
stuffedcrust = rbStuffedcrust.Text;
SummaryBox.Text = stuffedcrust;
}
private void button5_Click(object sender, EventArgs e)
{
Application.Exit();
}
private int clickCounter = 0;
private void button4_Click(object sender, EventArgs e) // Button to add the value pf the pizza to the text box
{
this.clickCounter++;
if (this.clickCounter < 10) // number of time the button can be pressed to add Pizzas
{
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
radioButton6.Checked = false;
radioButton7.Checked = false;
rbThinandcrispy.Checked = false;
rbStuffedcrust.Checked = false;
rbDeeppan.Checked = false;
checkBoxCrispyOnions.Checked = false;
checkBoxExtraCheese.Checked = false;
checkBoxPeppers.Checked = false;
checkBoxPepperoni.Checked = false;
checkBoxGarlicSauce.Checked = false;
checkBox12.Checked = false;
/*StreamWriter sw = new StreamWriter(SummaryBox.Text, true);
sw.WriteLine();
sw.WriteLine();
sw.WriteLine();
sw.WriteLine();
sw.Close(); */
MessageBox.Show("Pizza Added");
}
else
{
MessageBox.Show("No more Pizza's can be added, the maximum order is 10");
}
}
private void button7_Click(object sender, EventArgs e)
{
File.Create(textBox1.Text).Close();
}
private void button6_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.ShowDialog();
textBox1.Text = of.FileName;
}
public double PizzaPrice { get; set; } //Global Public
double ExtraTopping; //Global
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
string CT;
if (radioButton2.Enabled == true) //PIZZA CHEESE TOMATO
{
double ctp = 3.50;
PizzaPrice += ctp;
txtPizzaPrice.Text = "£ " + PizzaPrice.ToString();
CT = radioButton2.Text;
SummaryBox.Text = CT;
}
else
{
SummaryBox.Clear();
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
string VS;
if (radioButton1.Enabled == true) //PIZZA Veg SUpreme
{
double vsp = 5.20;
PizzaPrice += vsp;
txtPizzaPrice.Text = "£ " + PizzaPrice.ToString();
VS = radioButton1.Text;
SummaryBox.Text = VS;
}
else
{
SummaryBox.Clear();
}
}
private void radioButton3_CheckedChanged_1(object sender, EventArgs e)
{
string SV;
if (radioButton3.Enabled == true) //PIZZA SPicy Veg
{
double svp = 5.20;
PizzaPrice += svp;
txtPizzaPrice.Text = "£ " + PizzaPrice.ToString();
SV = radioButton3.Text;
SummaryBox.Text = SV;
}
else
{
SummaryBox.Clear();
}
}
private void radioButton6_CheckedChanged(object sender, EventArgs e)
{
string MF;
if (radioButton6.Enabled == true) //PIZZA MEAT FEAST
{
double mfp = 5.80;
PizzaPrice += mfp;
txtPizzaPrice.Text = "£ " + PizzaPrice.ToString();
MF = radioButton6.Text;
SummaryBox.Text = MF;
}
else
{
SummaryBox.Clear();
}
}
private void radioButton7_CheckedChanged(object sender, EventArgs e)
{
string HP;
if (radioButton7.Enabled == true) //PIZZA Ham pineapple
{
double hpp = 4.20;
PizzaPrice += hpp;
txtPizzaPrice.Text = "£ " + PizzaPrice.ToString();
HP = radioButton7.Text;
SummaryBox.Text = HP;
}
else
{
SummaryBox.Clear();
}
}
private void radioButton4_CheckedChanged(object sender, EventArgs e)
{
string SF;
if (radioButton4.Enabled == true) // PIZZA SEAFOOD
{
double sfp = 5.60;
PizzaPrice += sfp;
txtPizzaPrice.Text = "£ " + PizzaPrice.ToString();
SF = radioButton4.Text;
SummaryBox.Text = SF;
}
else
{
SummaryBox.Clear();
}
}
private void button1_Click(object sender, EventArgs e)
{
Bill sf = new Bill();
sf.Show(); // Open Bill
}
private void checkBox15_CheckedChanged(object sender, EventArgs e)
{ //EXTRA CHEESE
string EC;
if (checkBoxExtraCheese.Checked)
{
double ecp = .50;
ExtraTopping += ecp;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
EC = checkBoxExtraCheese.Text;
}
else
{
ExtraTopping = 0 + PizzaPrice;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
}
}
private void checkBox10_CheckedChanged(object sender, EventArgs e)
{ //PEPPERS
string PEP;
if (checkBoxPeppers.Checked)
{
double pepp = .50;
ExtraTopping += pepp;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
PEP = checkBoxPeppers.Text;
}
else
{
ExtraTopping = 0 + PizzaPrice;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
}
}
private void checkBoxCrispyOnions_CheckedChanged(object sender, EventArgs e)
{ //CRISPY ONIONS
string CO;
if (checkBoxCrispyOnions.Checked)
{
double cop = .50;
ExtraTopping += cop;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
CO = checkBoxCrispyOnions.Text;
}
else
{
ExtraTopping = 0 + PizzaPrice;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
}
}
private void checkBoxGarlicSauce_CheckedChanged(object sender, EventArgs e)
{ //Garlic Sauce
string GS;
if (checkBoxGarlicSauce.Checked)
{
double gsp = .50;
ExtraTopping += gsp;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
GS = checkBoxGarlicSauce.Text;
}
else
{
ExtraTopping = 0.0 + PizzaPrice;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
}
}
private void checkBoxPepperoni_CheckedChanged(object sender, EventArgs e)
{ //PEPPERONI
string Proni;
if (checkBoxPepperoni.Checked)
{
double pepperoni = .50;
ExtraTopping += pepperoni;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
Proni = checkBoxPepperoni.Text;
}
else
{
ExtraTopping = 0 + PizzaPrice;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
}
}
private void rbThinandcrispy_CheckedChanged(object sender, EventArgs e)
{ //Add type of crust to summary box
thincrispy = rbThinandcrispy.Text;
SummaryBox.Text = thincrispy;
}
private void rbDeeppan_CheckedChanged(object sender, EventArgs e)
{ //Add type of crust to summary box
Deeppan = rbDeeppan.Text;
SummaryBox.Text = Deeppan;
}
Menu(object sender, System.ComponentModel.CancelEventArgs e)
{
clickCounter--;
}
}
}
Your code is fairly confusing, particularly because of controls with names like radioButton1, radioButton2, etc...
It looks like your issue could be stemming from the fact that when your pizza type radio buttons change state, you add the price of the newly selected pizza to the pizza price instead of replacing it.
I would strongly encourage you to adopt an object-oriented approach in your application. If you create a Pizza class with fields for extra toppings, each Pizza that you add to an order will know everything that should be on it and how much it costs in total, and the Pizza could have a .ToString() overload that would build the summary text you're looking for: i.e., "Supreme pizza (4.50) : cheese (.50), crispy onions (.50) = Total: 5.50"
Separating your business objects from the UI elements (checkboxes, radio buttons, text fields) will vastly simplify what you're trying to do.
This is a guess but your add button only sets all your check boxes.Checked = false and then displays a popup. It never actually adds the price of the current pizza selected to any totals.
I get the following error when compiling:
CS0120: An object reference is required for the non-static field, method or property 'QuickSharp.CokeMachine.TotalInsertedCoins'
This is because I'm trying to use the TotalInsertedCoins variable from another class (CokeForm). How can I fix this? If I want to add the buttons in my CokeForm method, I'm getting the same issue.
My code:
using System;
using System.Windows.Forms;
using System.Drawing;
namespace QuickSharp
{
public class CokeMachine
{
Button Coke;
Button Sprite;
Button Fanta;
Button RedBull;
Button Juice;
Button Water;
double CokeCost = 1.00;
double SpriteCost = 1.00;
double FantaCost = 1.00;
double RedBullCost = 2.50;
double JuiceCost = 2.00;
double WaterCost = 0.50;
Button Coin1;
Button Coin2;
Button Coin3;
Button Coin4;
Button Coin5;
Button Coin6;
double CoinAmount1 = 0.05;
double CoinAmount2 = 0.10;
double CoinAmount3 = 0.20;
double CoinAmount4 = 0.50;
double CoinAmount5 = 1.00;
double CoinAmount6 = 2.00;
public double TotalInsertedCoins = 0;
//EventHandlers for drink buttons
public void DrinkButtonsEvents()
{
Coke.Click += new EventHandler(Coke_ClickHandler);
Sprite.Click += new EventHandler(Sprite_ClickHandler);
Fanta.Click += new EventHandler(Fanta_ClickHandler);
RedBull.Click += new EventHandler(RedBull_ClickHandler);
Juice.Click += new EventHandler(Juice_ClickHandler);
Water.Click += new EventHandler(Water_ClickHandler);
}
//Drink buttons - Click event handlers
public void Coke_ClickHandler(object sender, EventArgs e)
{
if(TotalInsertedCoins >= CokeCost)
{
DispenseDrink("Coca-Cola", CokeCost);
}
else
{
MessageBox.Show("You have not inserted enough money to buy this drink.", "Warning");
}
}
public void Sprite_ClickHandler(object sender, EventArgs e)
{
if(TotalInsertedCoins >= SpriteCost)
{
DispenseDrink("Sprite", SpriteCost);
}
else
{
MessageBox.Show("You have not inserted enough money to buy this drink.", "Warning");
}
}
public void Fanta_ClickHandler(object sender, EventArgs e)
{
if(TotalInsertedCoins >= FantaCost)
{
DispenseDrink("Fanta", FantaCost);
}
else
{
MessageBox.Show("You have not inserted enough money to buy this drink.", "Warning");
}
}
public void RedBull_ClickHandler(object sender, EventArgs e)
{
if(TotalInsertedCoins >= RedBullCost)
{
DispenseDrink("Red Bull", RedBullCost);
}
else
{
MessageBox.Show("You have not inserted enough money to buy this drink.", "Warning");
}
}
public void Juice_ClickHandler(object sender, EventArgs e)
{
if(TotalInsertedCoins >= JuiceCost)
{
DispenseDrink("Orange Juice", JuiceCost);
}
else
{
MessageBox.Show("You have not inserted enough money to buy this drink.", "Warning");
}
}
public void Water_ClickHandler(object sender, EventArgs e)
{
if(TotalInsertedCoins >= WaterCost)
{
DispenseDrink("Water", WaterCost);
}
else
{
MessageBox.Show("You have not inserted enough money to buy this drink.", "Warning");
}
}
//EventHandlers for money buttons
public void MoneyButtonEvents()
{
Coin1.Click += new EventHandler(Coin1_ClickHandler);
Coin2.Click += new EventHandler(Coin2_ClickHandler);
Coin3.Click += new EventHandler(Coin3_ClickHandler);
Coin4.Click += new EventHandler(Coin4_ClickHandler);
Coin5.Click += new EventHandler(Coin5_ClickHandler);
Coin6.Click += new EventHandler(Coin6_ClickHandler);
}
//Money buttons - Click event handlers
public void Coin1_ClickHandler(object sender, EventArgs e)
{
TotalInsertedCoins += CoinAmount1;
}
public void Coin2_ClickHandler(object sender, EventArgs e)
{
TotalInsertedCoins += CoinAmount2;
}
public void Coin3_ClickHandler(object sender, EventArgs e)
{
TotalInsertedCoins += CoinAmount3;
}
public void Coin4_ClickHandler(object sender, EventArgs e)
{
TotalInsertedCoins += CoinAmount4;
}
public void Coin5_ClickHandler(object sender, EventArgs e)
{
TotalInsertedCoins += CoinAmount5;
}
public void Coin6_ClickHandler(object sender, EventArgs e)
{
TotalInsertedCoins += CoinAmount6;
}
private void DispenseDrink(string drink , double cost)
{
if(TotalInsertedCoins - cost == 0.0)
{
MessageBox.Show("Enjoy your " + drink + "!");
TotalInsertedCoins = 0.0;
}
else
{
MessageBox.Show("Enjoy your " + drink + "! Here is your change: €" + (TotalInsertedCoins - cost));
TotalInsertedCoins = 0.0;
}
}
}
public class CokeForm : Form
{
public CokeForm()
{
// General aspect of machine
this.Text = "Cola Machine";
this.Size = new Size(450, 500);
Label Header;
Header = new Label();
Header.Text = "Coca-Cola Machine";
Header.Font = new Font("Arial", Header.Font.Size + 5);
Header.ForeColor = Color.DarkRed;
Header.Location = new Point(132, 20);
Header.AutoSize = true;
this.Controls.Add(Header);
TextBox TextBox1 ;
TextBox1 = new TextBox();
TextBox1.BackColor = Color.Black;
TextBox1.ForeColor = Color.Red;
TextBox1.Font = new Font("Arial", TextBox1.Font.Size + 3);
TextBox1.ReadOnly = true;
TextBox1.Size = new Size(210, 300);
TextBox1.Location = new Point(112, 50);
//TextBox1.SelectionStart = TextBox1.Text.Length;
//TextBox1.ScrollToCaret();
//TextBox1.Refresh();
if(CokeMachine.TotalInsertedCoins == 0.00)
{
TextBox1.Text = "Buy Your Ice Cold Drinks Here!";
}
else
{
TextBox1.Text = "Inserted Coins: €" + CokeMachine.TotalInsertedCoins;
}
this.Controls.Add(TextBox1);
// Money aspect of machine
Label Money;
Money = new Label();
Money.Text = "Insert Coins Here:";
Money.Location = new Point(20, 100);
this.Controls.Add(Money);
//Money buttons will be here
// Drink aspect of machine
Label Drinks;
Drinks = new Label();
Drinks.Text = "Choose Your Drink:";
Drinks.Location = new Point(315, 100);
Drinks.AutoSize = true;
this.Controls.Add(Drinks);
//Drink buttons will be here
}
}
public class Test
{
public static void Main()
{
CokeForm ColaForm;
ColaForm = new CokeForm();
Application.Run(ColaForm);
}
}
}
How do I fix this problem? Other questions about the CS0120 error don't bring me any further.
You never create an instance of CokeMachine:
if(CokeMachine.TotalInsertedCoins == 0.00)
{
TextBox1.Text = "Buy Your Ice Cold Drinks Here!";
}
else
{
TextBox1.Text = "Inserted Coins: €" + CokeMachine.TotalInsertedCoins;
}
Create an instance of CokeMachine in the form, and then use that.
...
CokeMachine machine = new CokeMachine();
...
if (machine.TotalInstertedCoins == 0.00)
{
....
}
I have a form that has two buttons, textbox, listbox, and a combobox. The problem I am having is when I am trying to total button. I can not figure out how to get the cost values from this list, so I can total the total cost of the order. Thanks for the suggestions.
private void Order_Click(object sender, EventArgs e)
{
amount = int.Parse(textBox1.Text);
cost *= amount;
if (comboBox1.SelectedItem.ToString() == "Eggs")
{
listBox1.Items.Add("The cost for " + amount + "
dozen large, fresh eggs is: " + (cost).ToString("C"));
comboBox1.Text = "";
textBox1.Text = "0";
textBox1.Focus();
comboBox1.Focus();
}
else if (comboBox1.SelectedItem.ToString() == "Milk")
{
if (amount == 1)
{
listBox1.Items.Add
("The Cost for a fresh quart milk is: " + (cost).ToString("C"));
comboBox1.Text = "";
comboBox1.Focus();
textBox1.Text = "0";
textBox1.Focus();
}
else
{
listBox1.Items.Add
("The Cost for " + amount + " quarts of fresh milk is: " +
(cost).ToString("C"));
comboBox1.Text = "";
comboBox1.Focus();
textBox1.Text = "0";
textBox1.Focus();
}
}
else
{
listBox1.Items.Add
("The Cost for " + amount + " fresh loafs of bread is: " + (cost).ToString("C"));
comboBox1.Text = "";
comboBox1.Focus();
textBox1.Text = "0";
textBox1.Focus();
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "Eggs")
{
cost = 1.90;
label1.Text = "The Cost is " + (cost).ToString("C") + " per dozen";
}
else if (comboBox1.SelectedItem.ToString() == "Milk")
{
cost = 1.47;
label1.Text = "The Cost is " + (cost).ToString("C") + " per quart";
}
else
{
cost = 2.12;
label1.Text = "The Cost is " + (cost).ToString("C") + " per loaf";
}
}
private void total_Click(object sender, EventArgs e)
{
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -2)
{
e.Handled = true;
}
if (e.KeyChar == '-'
&& (sender as TextBox).Text.IndexOf('-') > -2)
{
e.Handled = true;
}
}
}
}
Why not use a total class field and add the amount to it each time you add an item to the list box? Then you would always have the total cost without having to try to parse it back out of the list.
public partial class Form1 : Form
{
private double cost;
private double total;
int amount = 0;
public Form1()
{
InitializeComponent();
}
private void Order_Click(object sender, EventArgs e)
{
amount = int.Parse(textBox1.Text);
cost *= amount;
total += cost;
...
}