I'm creating a program that allows the user to choose 2 different options, 1 for the dormitories and 1 for the meal plan. I'm using radio buttons for both, but I can only choose 1 button at a time, and I want to be able to choose both at the same time
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
int totalCharge = 0;
totalCharge = Dorm() + MealPlan();
Form1 TChargeForm = new Form1();
TChargeForm.label1.Text = totalCharge.ToString("c");
TChargeForm.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
radioButton5.Checked = false;
radioButton6.Checked = false;
radioButton7.Checked = false;
}
private int Dorm()
{
int total = 0;
if (radioButton1.Checked)
{
total += 1500;
return total;
}
if (radioButton2.Checked)
{
total += 1600;
return total;
}
if (radioButton3.Checked)
{
total += 1500;
return total;
}
if (radioButton4.Checked)
{
total += 1500;
return total;
}
else
{
return total;
}
}
private int MealPlan()
{
int total = 0;
if (radioButton5.Checked)
{
total += 600;
return total;
}
if (radioButton6.Checked)
{
total += 1200;
return total;
}
if (radioButton7.Checked)
{
total += 1700;
return total;
}
else
{
return total;
}
}
}
Try using the GroupName property for each type of button: dorimitories, mealplan
Groupname attribute allows you to create logical groups of selections for radio buttons.
Add this attribute to every radio button or at the group box level.
Related
I am beginning with C#. When I run the following code and click the generate button the output does not appear in the textbox. Why is this? I am calling the function palendrome and its not updating the textbox. What am I doing wrong? Am I missing something? What do I need to fix. I don't see the error. Please help. :(
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PalendromeChecker
{
public partial class Form1 : Form
{
int num;
int count;
static int result;
int setPalendromeValue;
int copyCount;
public Form1()
{
InitializeComponent();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
count = Int32.Parse(textBox2.Text);
copyCount = count;
if (!int.TryParse(textBox2.Text, out count))
{
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
else if (count < 0 || count > 100)
{
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
}
public static int palendrome(int num)
{
int temp = num; ;
int r;
int rv = 0;
while (num > 0)
{
r = num % 10;
rv = rv * 10 + r;
num /= 10;
}
if (rv == temp)
{
result = temp;
return temp;
}
else
{
return 0;
}
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
while (copyCount != 0)
{
string resultInString = result.ToString();
textBox3.Text = resultInString;
textBox3.Visible = true;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
num = Int32.Parse(textBox1.Text);
//MessageBox.Show(this.textBox1.Text);
if (!int.TryParse(textBox1.Text, out num))
{
//MessageBox.Show("This is a number only field");
//return;
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
else if (num < 0 || num > 1000000000)
{
// MessageBox.Show("Invalid Input needs to be between 0 and 1,000,000,000");
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
label4.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
int palendromeValue;
while (count != 0)
{
palendromeValue = palendrome(num);
count--;
}
}
}
}
It is not generating any input on the textbox because your function palendrome is not generating in anyway output on any of textbox1 to textbox3.
Try this:
textBox1.Text = "output"; //Whatever output you want.
If you want to show result in textBox3 the code to update it's text property should be inside button click handler, not in text changed handler.
Also while (count != 0) or while (copyCount != 0) are like infinite loops (almost). They are going to make your form unresponsive. You need to avoid those.
This question already has an answer here:
Interaction between forms — How to change a control of a form from another form?
(1 answer)
Closed 6 years ago.
On one Form, the Quiz form, I have an integer score which keeps track of the user's score. On another Form, the Game Over form, I need to print out the score of the user, but even after hours of me attempting to do so, I still can't manage to do it. I know my code could be improved by A LOT but I just need help to solve this problem and would appreciate it. I just started out on C# and I just wanted to experiment on things.
namespace Quiz_Application
{
public partial class Quiz : Form
{
static Random gen = new Random();
int[] rand = Enumerable.Range(1, 5).OrderBy(q => gen.Next()).ToArray();
int i = 0;
int score = 0;
int[] goArray = new int[1];
public void Question1()
{
questionText.Text = "What is the capital city of Spain?";
optionA.Text = "Barcelona";
optionB.Text = "Madrid";
optionC.Text = "Seville";
optionD.Text = "Zarazoga";
}
public void Question2()
{
questionText.Text = "What is the biggest island on Earth?";
optionA.Text = "Luzon";
optionB.Text = "Singapore";
optionC.Text = "Greenland";
optionD.Text = "Hawaii";
}
public void Question3()
{
questionText.Text = "What is the world's longest river?";
optionA.Text = "Nile";
optionB.Text = "Amazon";
optionC.Text = "Mississipi";
optionD.Text = "Congo";
}
public void Question4()
{
questionText.Text = "Which country is Prague in?";
optionA.Text = "Czech Republic";
optionB.Text = "Slovakia";
optionC.Text = "Austria";
optionD.Text = "Poland";
}
public void Question5()
{
questionText.Text = "What is the diameter of Earth?";
optionA.Text = "6,779km";
optionB.Text = "3,474km";
optionC.Text = "12,742km";
optionD.Text = "8,721km";
}
static void Wait(double sec)
{
Task.Delay(TimeSpan.FromSeconds(sec)).Wait();
}
public Quiz()
{
InitializeComponent();
}
private void Quiz_Load(object sender, EventArgs e)
{
}
public void label1_Click(object sender, EventArgs e)
{
scoreNum.ResetText();
score = 0;
int goScore = goArray[0];
this.Hide();
Form1 f1 = new Form1();
f1.ShowDialog();
this.Close();
}
private void optionClick(object sender, EventArgs e)
{
startButton.Enabled = false;
Button l = (Button)sender;
int[] goArray = new int[1];
goArray[0] = score;
if (l.Text == "Madrid" || l.Text == "Greenland" || l.Text == "Amazon" || l.Text == "Czech Republic" || l.Text == "12,742km")
{
score++;
scoreNum.Text = score.ToString();
correctOrWrong.Image = Resources.correct; Wait(1); correctOrWrong.Image = null;
}
else
{
correctOrWrong.Image = Resources.wrong; Wait(1); correctOrWrong.Image = null;
}
l.BackColor = System.Drawing.Color.Maroon;
optionA.Enabled = false; optionB.Enabled = false; optionC.Enabled = false; optionD.Enabled = false;
startButton.Enabled = true;
}
private void startButton_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
optionA.Enabled = true; optionB.Enabled = true; optionC.Enabled = true; optionD.Enabled = true;
if (i == 5)
{
scoreNum.ResetText();
score = 0;
int goScore = goArray[0];
b.Text = "Finish";
this.Hide();
Game_Over go = new Game_Over();
go.ShowDialog();
this.Close();
}
try
{
switch (rand[i])
{
case 1:
Question1();
i++;
break;
case 2:
Question2();
i++;
break;
case 3:
Question3();
i++;
break;
case 4:
Question4();
i++;
break;
case 5:
Question5();
i++;
break;
case 6:
Wait(2);
this.Hide();
Game_Over go = new Game_Over();
go.ShowDialog();
this.Close();
break;
}
if (i == 5)
{
b.Text = "Finish";
}
}
catch { }
if (i != 5)
b.Text = "Next";
b.Enabled = false;
}
private void mouseEnter(object sender, EventArgs e)
{
this.Cursor = Cursors.Hand;
}
private void mouseLeave(object sender, EventArgs e)
{
this.Cursor = Cursors.Default;
}
public int get(int i)
{
return i;
}
}
and my Game Over form
namespace Quiz_Application
{
public partial class Game_Over : Form
{
public Game_Over()
{
InitializeComponent();
}
private void Game_Over_Load(object sender, EventArgs e)
{
Quiz q = new Quiz();
}
private void playAgain_Click(object sender, EventArgs e)
{
Quiz q = new Quiz();
this.Hide();
q.ShowDialog();
this.Close();
}
private void mainMenu_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
this.Hide();
f1.ShowDialog();
this.Close();
}
}
Create a public class and store the value in it, you can access the value across the code.
class Globals
{
public static int Score = 0;
}
// In the window you can assign value for the variable like below
Globals.Score=<Your score>;
In the Game_Over form, add a label to display the score if you haven't done so already. I will call it myScoreLabel Then, when you show the form i.e. here:
case 6:
Wait(2);
this.Hide();
Game_Over go = new Game_Over();
go.ShowDialog();
this.Close();
break;
add this line before go.ShowDialog:
go.yourScoreLabel.Text = "Score: " + score.ToString();
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);
}
}
I have created a code for my combobox, that can search addresses in a very large table on Sql Server with the help of stored procedure (i'm working with Entity framework). My stored procedure returns 10 hits and my code fills the combobox with search results. For doing this I'm using BackgroundWorker.
But here I'm now having big problems:
- although the combobox is filled with my search results, it always has the first item selected. Even if I type in only a letter, the whole text gets selected;
After that searching for the address doesn't work anymore. It searches only among these 10 results and I'm having no idea how to solve this. Here is my whole code, that causes me problems:
public String searchedItem = "";
public delegate void DelegateUpdateComboboxSelection(ComboBox myCombo,string value,int count);
BackgroundWorker m_bgworker = new BackgroundWorker();
static AutoResetEvent resetWorker = new AutoResetEvent(false);
m_bgworker.WorkerSupportsCancellation = true;
m_bgworker.DoWork += new DoWorkEventHandler(FillComboboxBindingList);
m_bgworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_bgworker_RunWorkerCompleted);
BindingList<spIskalnikNaslovi_Result1> m_addresses = new BindingList<SP_Result1>();
void m_bgworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
int count = (int)((object[])e.Result)[0];
string value = (string)((object[])e.Result)[1];
ComboBox myCombo = (ComboBox)((object[])e.Result)[2];
DelegateUpdateComboboxSelection ndelegate = new DelegateUpdateComboboxSelection(UpdateComboSelection);
if (this.InvokeRequired)
{
Invoke(ndelegate, new object[] {myCombo, value, count});
return;
}
else
{
UpdateComboSelection(myCombo, value, count);
return;
}
}
private void UpdateComboSelection(ComboBox myCombo, String value, int count)
{
myCombo = comboBox9;
myCombo.DataSource = m_addresses;
searchedItem = myCombo.Text;
if (count > 0)
{
myCombo.SelectionStart = value.Length;
myCombo.SelectionLength = searchedItem.Length - value.Length;
myCombo.DroppedDown = true;
}
else
{
myCombo.DroppedDown = false;
myCombo.SelectionStart = value.Length;
}
}
public void FillComboboxBindingList(object sender, DoWorkEventArgs e)
{
if (m_bgworker.CancellationPending)
{
resetWorker.Set();
e.Cancel = true;
return;
}
else
{
string value = (String)((Object[])e.Argument)[0];
List<SP_Result1> result;
result = _vsebina.SP_searcher(value).ToList<SP_Result1>();
m_addresses = new BindingList<SP_Result1>();
foreach (SP_Result1 rez in result)
{
if (m_addresses.Contains(rez))
{
continue;
}
else
{
m_addresses.Add(rez);
}
}
foreach (SP_Result1 r in m_addresses.ToArray())
{
if (!result.Contains(r))
{
m_addresses.Remove(r);
}
}
e.Result = new object[] { rezultat.Count, vrednost, null };
return;
}
}
private void comboBox9_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
int searchStart = comboBox9.SelectionStart;
if (searchStart > 0)
{
searchStart--;
if (searchStart == 0)
{
comboBox9.Text = "";
}
else
{
comboBox9.Text = comboBox9.Text.Substring(0, searchStart + 1);
}
}
else
{
searchStart = 0;
}
e.Handled = true;
}
}
private void comboBox9_Enter(object sender, EventArgs e)
{
comboBox9.SelectionStart = 0;
comboBox9.SelectionLength = 0;
}
private void comboBox9_Click(object sender, EventArgs e)
{
comboBox9.Text = "";
}
private void comboBox9_KeyPress(object sender, KeyPressEventArgs e)
{
Search();
}
public void Search()
{
if (comboBox9.Text.Length < 4)
{
return;
}
else
{
if (m_bgworker.IsBusy)
{
m_bgworker.CancelAsync();
m_bgworker = new BackgroundWorker();
m_bgworker.WorkerSupportsCancellation = true;
m_bgworker.DoWork += new DoWorkEventHandler(FillComboboxBindingList);
m_bgworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_bgworker_RunWorkerCompleted);
}
m_bgworker.RunWorkerAsync(new object[] { comboBox9.Text, comboBox9 });
}
}
Maybe can someone enlighten me, what I'm doing wrong. This is first time, that I'm using BackgroundWorker. I have no idea, how
to achieve "search as you type" with combobox in any other way, because my datatable with addresses is quite large (million records).
Thanks in advance for any kind of help or code example.
Vladimir
Edit 1:
Ok, here is my code, before I have used BackGroundWorker. It worked, but it searches very very slow (it can take up to 10 seconds):
private void comboBox9_TextChanged(object sender, EventArgs e)
{
if (comboBox9.Text.Length < 4)
{
return;
}
else
{
FillCombobox(comboBox9.Text, comboBox9);
}
}
public void FillCombobox(string value, ComboBox myCombo)
{
List<spIskalnikNaslovi_Result1> result;
result = _vsebina.spIskalnikNaslovi1(value).ToList();
if (result.Count() > 0)
{
myCombo.DataSource = result;
myCombo.ValueMember = "HS_MID";
myCombo.DisplayMember = "NASLOV1";
var searchedItem = myCombo.Items[0].ToString();
myCombo.SelectionStart = value.Length;
myCombo.SelectionLength = searchedItem.Length - value.Length;
myCombo.DroppedDown = true;
}
else
{
myCombo.DroppedDown = false;
myCombo.SelectionStart = value.Length;
}
return;
}
Is there a way to speed this up without having backgroundworker?
make a button you will call searchbutton
and in click_event of this button call your search() method that run your backgroundworker
that fill the combobox
clear you key_press event of your combobox and it will work
the mistake is you key_press event that call every key stroke happening your search method
so retrieve it
You should get your items in a list, use that list to populate your combobox.
then set AutoCompleteMode property value to Suggest or Append or SuggestAppend and set AutoCompleteSoucre property value to ListItems.
For "Search as you Type", which is actually "Filter as you Type" more than search, you need to implement the OnKeyDown or KeyPressed event.
What you would do is take the search string, which is the current text at the time of the event, then filter the master list using that string. Normally one would use "Starts With" for the filtering, but you could also simply use "Contains". Then you live update the contents of the box with the results from the filter. This is accomplished by changing and refreshing the Datasource.
Here is my final solution without BackGroundWorker. It works quick with my large table, and is upgraded for using a stored procedure on SQL Server (if you use Entity Framework). I use Timer to make sure the user can find a value, that he is searching.
Here you can see the original solution, that I found on this site (thanks to Max Lambertini and algreat for the idea and working concept):
C# winforms combobox dynamic autocomplete
My solution:
private bool _canUpdate = true;
private bool _needUpdate = false;
List<spIskalnikNaslovi_Result1> dataFound;
private void comboBox12_TextChanged(object sender, EventArgs e)
{
if (_needUpdate)
{
if (_canUpdate)
{
_canUpdate = false;
refreshData();
}
else
{
restartTimer();
}
}
}
private void comboBox12_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
int searchStart = comboBox12.SelectionStart;
if (searchStart > 0)
{
searchStart--;
if (searchStart == 0)
{
comboBox12.Text = "";
}
else
{
comboBox12.Text = comboBox12.Text.Substring(0, searchStart + 1);
}
}
else
{
searchStart = 0;
}
e.Handled = true;
}
}
private void comboBox12_TextUpdate(object sender, EventArgs e)
{
_needUpdate = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
_canUpdate = true;
timer1.Stop();
refreshData();
}
private void refreshData()
{
if (comboBox12.Text.Length > 1)
{
FillCombobox(comboBox12.Text, comboBox12);
}
}
private void restartTimer()
{
timer1.Stop();
_canUpdate = false;
timer1.Start();
}
private void FillCombobox(string value, ComboBox myCombo)
{
dataFound = _vsebina.spIskalnikNaslovi1(value).ToList();
if (dataFound.Count() > 0)
{
myCombo.DataSource = dataFound;
myCombo.ValueMember = "HS_MID";
myCombo.DisplayMember = "NASLOV1";
var searchedItem = myCombo.Items[0].ToString();
myCombo.SelectionStart = value.Length;
myCombo.SelectionLength = searchedItem.Length - value.Length;
myCombo.DroppedDown = true;
return;
}
else
{
myCombo.DroppedDown = false;
myCombo.SelectionStart = value.Length;
return;
}
}
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)
{
....
}