Creating a meal Cost calculator C# - c#

I'm trying to create a Meal Cost Calculator using C#.
Here is my current code
public partial class Form1 : Form
{
const double TAX_RATE = .076;
const double EXTRA_DISCOUNT = .1;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void tiplistBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if ((lessThanButton.Checked == true) && (moreThanButton.Checked == false)) ;
{
int selectedIndex = tiplistBox1.SelectedIndex;
switch (selectedIndex)
{
case 1:
break;
}
}
}
private void calculateButton_Click(object sender, EventArgs e)
{
int mealCost = int.Parse(mealCostBox1.Text);
double tax = (mealCost * TAX_RATE) + mealCost;
double disc = (tax * EXTRA_DISCOUNT);
double tipRate = (tax - disc);
double totalCost = (tipRate);
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
int count = 1;
if ((lessThanButton.Checked == true) && (moreThanButton.Checked == false))
{
tiplistBox1.Items.Add("");
for (count = 10; count <= 35; count += 5)
tiplistBox1.Items.Add("Tip Rate: " + count + "%");
count++;
}
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
int count = 1;
if ((lessThanButton.Checked == false) && (moreThanButton.Checked == true))
{
tiplistBox1.Items.Add("");
for (count = 15; count <= 35; count += 5)
tiplistBox1.Items.Add("Tip Rate: " + count + "%");
count++;
}
}
}
The user must enter the amount of the meal.
Then the user selects a radio button that asks how many people ate. (one RB is for less than 6 and the other is for more than 6.) this button is used in order to give tip rates which are displayed in tiplistBox1 (if <6 ppl = 10,15,20,25,30,35, if >6 ppl 15,20,25,30,35) The user must also identify if there is any type of discount, which is selected from checking one of three boxes (student, military or senior) if either one is selected a 10% discount is added. Once all is selected the calculate button is supposed to take the mealCost add the TAX_RATE, take any discounts off and if a tip rate is selected from the tiplistBox1 options, add the tipRate then give the amount due.
Right now, my project isn't complete, there are a few issues, first of all, as you can see, I'm not using the If,Else statements, I'm required to use switch statements, when I'm running the program from the start I'm getting the tipRate's to display correctly for example, if I select the RB that is <6 people, then the tipRates shown are 10,15,20,25,30,35. If instead, from the start I select RB that is >6 people then the tipRates 15,20,25,30,35 are shown. That's good, but when I try to switch the RB within the ongoing program the TipRates get added underneath the first set of tipRates
, also since I'm using switch statements, if I select either of the RB, the displayed tipRates don't match up, meaning if I create a case 1: in one instance it shows 10% but in another is shows 15%, which messes with the calculation process.
I need help!
How can I ensure that the tipRate selected will make sence in the calculation.
for example if in case 1: it shows 15% but only does the math for 10% tipRate.

...but when I try to switch the RB within the ongoing program the TipRates get added underneath the first set of tipRates
That's because you need to clear the list before adding the new set of rates to the list.
Call tiplistBox1.Items.Clear() before calling tiplistBox1.Items.Add("").

Related

Re-Enabling Button Based on Condition (C#)

What I am trying to do is simple (I cannot figure it out of course). I am making a sample shop with an inventory system in Winform App format where if on the customer side the "Place Order" button is clicked it deducts from inventory; the amount deducted depends on the quantity of the item ordered. Anyway with this code,
private void button7_Click(object sender, EventArgs e)
button7.Enabled = true;
//Read in value
int qty = Convert.ToInt32(nudQuantity.Value);
if ((rdoSmallCup.Checked & rdoStraw.Checked) == true) {
//Removing four from inventory for strawberry after an order is made
InvStrawberry = InvStrawberry - (4 * qty);
if (InvStrawberry <= 0) {
button7.Enabled = false;
} else {
button7.Enabled = true;
}
label17.Text = Convert.ToString(InvStrawberry);
I am seeing that while it does compile with no errors once the inventory for strawberry has fallen past zero (it will actually be a negative value which I do not want but is another question for another time) the Place Order button ("Button 7") will be grayed out and unusable which is the goal but once inventory is added again this button is still unusable. Can someone explain how I can have this button re-enabled (even though I said it in the 'else' condition)?
Ron and Heretic's comments are right. You cannot access the code in Button7 click event handler once it has been 'disabled'. The only way to enable it again is from outside logic, say after you added additional items into the inventory, you can enable the button right after that.
Also you can can be simplify a bit:
private void button7_Click(object sender, EventArgs e)
//Read in value
int qty = Convert.ToInt32(nudQuantity.Value);
if ((rdoSmallCup.Checked & rdoStraw.Checked) == true) {
//Removing four from inventory for strawberry after an order is made
InvStrawberry = InvStrawberry - (4 * qty);
if (InvStrawberry <= 0)
button7.Enabled = false;
label17.Text = Convert.ToString(InvStrawberry);
...
This code will allow an infinite number of subtraction. Hence, you will need a control that will stop the subtraction when you go below zero.
private void button7_Click(object sender, EventArgs e){
// I have no idea why you have enabled the button here, mate
//Converting the quantity
int qty = Convert.ToInt32(nudQuantity.Value);
if((roSmallCup.Checked & rdoStraw.Checked) == true) {
//triggers when the Inventory of strawberry is more than zero
if( (InvStrawberry - (4 * qty)) > 0 ){
InvStrawberry = InvStrawberry - (4 * qty);
} else
{
button7.ENabled = false;
MessageBox.Show("We are out of inventory,Sorry!");
}
label17.Text = Convert.ToString(InvStrawberry);
}
}
If you want the button to possibly update every time that you change the value of InvStrawberry then the best option is to make a property for InvStrawberry and update the status of the button there. That cuts down the logic that you need to use right throughout your code.
Try this:
public class StrawberryForm : Form
{
private int _invStrawberry = 0;
private int InvStrawberry
{
get
{
return _invStrawberry;
}
set
{
_invStrawberry = value;
button7.Enabled = _invStrawberry > 0;
}
}
private void button7_Click(object sender, EventArgs e)
{
int qty = Convert.ToInt32(nudQuantity.Value);
if ((rdoSmallCup.Checked & rdoStraw.Checked) == true)
{
this.InvStrawberry -= 4 * qty;
label17.Text = Convert.ToString(this.InvStrawberry);
}
}
}
you need to move this:
if (InvStrawberry <= 0) {
button7.Enabled = false;
} else {
button7.Enabled = true;
}
to an Updae method or loop that will check it regularly, right now its in your click, and therefore will never get called to enable it again once it is disabled, since at that point you cant click on it.
also, say you have two variables, numberStrawberries representing youre remaining inventory, and lot representing the four strawberries you put in a purchase...
if(numberStrawberries >= lot){
//we have strawberries, and more at least 4 or more
numberStrawberries-=lot;
}else if(numberStrawberries!=0 && numberStrawberries < lot){
//we have strawberries but only (remaining)
//how many were short(how many we have is still in numberStrawberries)
int short = lot- numberStrawberries;
numberStrawberries=0;
}else{
//all out of strawberries
}

Windows Form App Float to String

Below is some of my code that isn't working. I wanted to see it could count the number of spaces in the text box so I'm having it display the number in a message box and it currently just throws a blank one. The problem is either in the float to string conversion or in the counter.
private static string _globalVar = "n";
public static string GlobalVar
{
get { return _globalVar; }
set { _globalVar = value; }
}
public Form1()
{
InitializeComponent();
button1.Text = "Enter";
}
string LNum { get; set; }
public void button1_Click_1(object sender, EventArgs e)
{
MessageBox.Show(LNum);
}
public void richTextBox1_TextChanged(object sender, System.Windows.Forms.KeyEventArgs e)
{
float n = 0;
if (Control.ModifierKeys == Keys.Space)
{
n = n + 1; ;
}
string.Format("{0:N1}", n);
string LNum = Convert.ToString(n);
}
What you are doing is an excellent way to learn how and when the events are raised and how they can be leveraged to customize an applications behavior and is something similar to what many of us have done over the years.
Based on what you say you are wanting to do, there are several issues. If you take a look at this code, it will do what you want.
public void button1_Click(object sender, EventArgs e)
{
int n = 0;
for (int counter = 0; counter < richTextBox1.TextLength; counter++)
{
if (richTextBox1.Text[counter] == ' ')
{
n++;
}
}
MessageBox.Show(n.ToString("N1"));
}
The key difference is that I am only looking at the entered text when the button is clicked. (TextChanged is run every time there is a change in the text displayed). I chose not to use a float variable to store the count of spaces as the count will always be an integer.
In addition, the parameter to TextChanged System.Windows.Forms.KeyEventArgs e is incorrect and will never compile if correctly bound to the TextChanged event.
The KeyEventArgs parameter is used by the KeyUp and KeyDown events. If you use these events, you will be looking to count every time the space bar is pressed and not the number of spaces in the text box. And like their name suggests, the events are raised every time a Key on the keyboard goes Up (Pressed) and Down (Released).

Adding Summary Variables

I have an asp.net website with two forms. The first form contains input controls for a user to enter shipping information. The second form contains summary information. The problem I have is that when a user adds an item by pressing the addButton on the first form, they should be able to enter another item and the sum of the price of those items should be passed to the summary form, instead it just passes the price of the most current item entered after addButton is clicked. I'm just beginning asp.net so any help would be appreciated.
protected void addButton_Click(object sender, EventArgs e)
{
var dollA = new List<decimal>();
int i = 0;
for (i = 0; i < 4; i++) {
weightInteger = int.Parse(weightTextBox.Text);
quantityInteger = int.Parse(quanTextBox.Text);
priceDecimal = decimal.Parse(priceTextBox.Text);
// Calculate the current item price.
currentPriceDecimal = priceDecimal * quantityInteger;
// Format and display the current item price.
currentTextBox.Text = currentPriceDecimal.ToString("C");
// Calculate the dollar amount due.
dollarAmountDecimal += currentPriceDecimal;
dollA.Add(dollarAmountDecimal);
dollDec = dollA.Sum();
Session["Amount"] = dollDec;
}
}
Summary Form:
protected void Page_Load(object sender, EventArgs e)
{
decimal amount;
amount = Convert.ToDecimal(Session["Amount"]);
amountTextBox.Text = amount.ToString("C");
}
This seemed to work for the OP based on the comments.
protected void addButton_Click(object sender, EventArgs e)
{
if (Session["Amount"] == null)
Session["Amount"] = Decimal.Zero;
weightInteger = int.Parse(weightTextBox.Text);
quantityInteger = int.Parse(quanTextBox.Text);
priceDecimal = decimal.Parse(priceTextBox.Text);
// Calculate the current item price.
currentPriceDecimal = priceDecimal * quantityInteger;
// Format and display the current item price.
currentTextBox.Text = currentPriceDecimal.ToString("C");
// Calculate the dollar amount due.
dollarAmountDecimal += currentPriceDecimal;
Session["Amount"] = (decimal)Session["Amount"] + dollarAmountDecimal;
}

C# Limited times a button can be pressed with pop up showing and streamwriting to a file

Okay so I am writing a program and it should only allow the user to click a certain Button a random amount of times (1-25 times) which is generated each time the user starts the program. My code is not working for this, the program currently keeps a totalled Value in a ListBox and when the user hits the "limit" amount that they can hit the button, its suppose to write that totalled value to a file which I already have saved. Also how would you incorporate the Message show when this 'Random number of times' is activated? Here is my code, THanks:
public Form1()
{
InitializeComponent();
}
private int lose()
{
// int High_Score;
Random rand = new Random();
lost = rand.Next(23) + 2;
return lost;
MessageBox.Show(" you lose");
}
private void begingameButton_Click(object sender, EventArgs e)
{
lose();
//Begin game button disable
begingameButton.Enabled = false;
//The roll button is enabled
rolldieButton.Enabled = true;
//Makes the beginning instructions visible
beginLabel.Visible = false;
//Makes the other instructions visible
diceBox1.Visible = true;
//Enables the start over button
startoverButton.Enabled = true;
//Displays a total of 0 dollars at the beginning of game
int beginTotal = 0;
totalmoneyLabel.Text = beginTotal.ToString("c");
}
You need to initialize the Random class only once, otherwise you'll get the same number each time you call .Next().
Assuming the roll button is the one that needs to have a limited number of clicks...
private Random Rand = new Random();
private int RollCount;
private int RollLimit;
private void begingameButton_Click(object sender, EventArgs e)
{
RollCount = 0;
RollLimit = Rand.Next(1, 25);
//...other prep work
}
private void rolldieButton_Click(object sender, EventArgs e)
{
RollCount++;
if (RollCount == RollLimit)
{
// limit reached
}
}

converting textbox string to int

I'm trying to compare and multiply 2 random number variables with the int value entered in textboxes. If it is the correct increment the correct answers it does not increase the number although it increment works alone but it does not work with the textbox.
private void button1_Click(object sender, EventArgs e)
{
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
//int cv = +correct;
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
int s = x * z;
if (s == int.Parse(textBox4.Text))
{
correct++;
numbercorrect.Text = correct.ToString();
}
}
EDIT This is assuming that you are trying to have the user enter their guess before the button is pressed. Figured I would put this disclaimer here since there is confusion exactly what you are trying to do.
Looking at your current code sample, you are trying parse textBox4.Text, however, you are not setting textBox4.Text anywhere in your code sample. If textBox4.Text is string.Empty, int.Parse will throw an exception.
You should also look into doing Int.TryParse as it will tell you if it worked without throwing an exception.
EDIT: Since this is a guessing game, you should be validating the user's entry in textBox4 before continuing.
private void button1_Click(object sender, EventArgs e)
{
int answer;
if(!int.TryParse(textBox4.Text, out answer))
{
MessageBox.Show("Please Enter A Valid Integer.");
return;
}
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
//int cv = +correct;
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
int s = x * z;
if (s == answer)
{
correct++;
numbercorrect.Text = correct.ToString();
}
}
You're comparing the textbox value to the product of two random values. Unless you know what those two random numbers are before you push the button, the if will fail.
This subroutine will be run as soon as Button1 is pressed. This will display two random numbers for the user to multiply. (Displayed in TB2 and TB3.)
Now, as soon as these numbers are displayed (and before the user has a chance to enter any answer) the program checks the value in TB4. This is empty, and throws an error when the parse is attempted.
Try breaking this into 2 subroutines with 2 buttons: one button to display a new problem, and one button to check the answer.
EDIT: Code added. (Note: I wrote this freehand--don't know if it would compile or not... just get the general idea. Note the button names.)
//This routine sets up the problem for the user.
private void btnGenerateProblem_Click(object sender, EventArgs e) {
//Get 2 random factors
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
//Display the two factors for the user
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
}
//This routine checks the user's answer, and updates the "correct count"
private void btnCheckAnswer_Click(object sender, EventArgs e) {
//Get the random numbers out of the text boxes to check the answer
int x = int.Parse(textBox2.Text);
int z = int.Parse(textBox3.Text);
//Compute the true product
int s = x * z;
//Does the true product match the user entered product?
if (s == int.Parse(textBox4.Text)) {
correct++;
numbercorrect.Text = correct.ToString();
}
}
Add verification code at the beginning of btnCheckAnswer_Click.
private void button1_Click(object sender, EventArgs e)
{
int result = Convert.ToInt32(textBox4.Text); int x, z;
if (Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text) == result)
{
correct++;
numbercorrect.Text = correct.ToString();
Randomnumber.Next(12);
textBox2.Text = Randomnumber.Next(12).ToString();
textBox3.Text = Randomnumber.Next(12).ToString();
}
}

Categories