I have this program that I am working on for class, I think the problem is in my if statements. When I run the program and make my selection and click the total button and I get this as a display "for your appetizer, for your entree, and for dessert" in the order label and the price for the steak dinner in the order total label. I think I may have to use switch statements, but I'm not sure any suggestions would be of great help, thanks.
namespace Restaurant
{
public partial class frmRestaurant : Form
{
decimal AppetizerPrice = 0.0m;
decimal EntreePrice = 0.0m;
decimal DessertPrice = 0.0m;
decimal total = 0.0m;
string AppetizerOrder = "", EntreeOrder = "", DessertOrder = "", order = "";
public frmRestaurant()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnTotal_Click(object sender, EventArgs e)
{
CalculateTotal();
Order();
lblOrder.Text = order;
lblTotal.Text = total.ToString();
}
private void grpAppetizer_Enter(object sender, EventArgs e)
{
if (radCheeseSticks.Checked)
{
AppetizerPrice = 5.99m;
AppetizerOrder = "Cheese Sticks";
}
else if (radGarlicBread.Checked)
{
AppetizerPrice = 4.50m;
AppetizerOrder = "Garlic Bread";
}
else if (radChipsnSalsa.Checked)
{
AppetizerPrice = 3.50m;
AppetizerOrder = "Chips and Salsa";
}
}
private void grpEntree_Enter(object sender, EventArgs e)
{
if (radSteakDinner.Checked)
{
EntreePrice = 12.50m;
EntreeOrder = "Steak Dinner";
}
else if (radChickenParm.Checked)
{
EntreePrice = 10.99m;
EntreeOrder = "Chicken Parmigiana";
}
else if (radChipsnSalsa.Checked)
{
EntreePrice = 3.50m;
EntreeOrder = "Chips and Salsa";
}
}
private void grpDessert_Enter(object sender, EventArgs e)
{
if (radSteakDinner.Checked)
{
DessertPrice = 12.50m;
DessertOrder = "Steak Dinner";
}
else if (radChickenParm.Checked)
{
DessertPrice = 10.99m;
DessertOrder = "Chicken Parmigiana";
}
else if (radChipsnSalsa.Checked)
{
DessertPrice = 3.50m;
DessertOrder = "Chips and Salsa";
}
}
public decimal CalculateTotal()
{
total = AppetizerPrice + EntreePrice + DessertPrice;
return total;
}
public string Order()
{
order = AppetizerOrder + "for your appetizer," + EntreeOrder + "for your entree, and " + DessertOrder + "for dessert";
return order;
}
}
}
I think the GroupBox.Enter event is not useful for your use case. The enter event is invoked sometime during the control activation, but not when the value is changed.
One way to fix your problem is to set the appetizer/entree/dessert price and text only when the "Total" button is clicked. You do not need it before that in the current form right now.
Another way to fix it is to use the correct event: Just handle the RadioButton.CheckedChanged event for all of those radio buttons, for example:
private void radGarlicBread_CheckedChanged(object sender, EventArgs e)
{
if (radGarlicBread.Checked)
{
AppetizerPrice = 4.50m;
AppetizerOrder = "Garlic Bread";
}
}
First of all, you probably want to use String.Format(), because it'll look a bit cleaner than a bunch of concatenation--it'll also help you catch things like the lack of spaces here (your output seems like it would be, e.g. 'Chips and Salsafor your appetizer...')
It might also be better to just find whichever item is checked in the Order method rather than update it every time the user checks.
I'm not sure what is wrong, but maybe you can do a Debug.WriteLine() every time each of the Enter() methods is called to see what is going on.
For example:
Debug.WriteLine("grpDesert_Enter");
Debug.WriteLine(radSteakDinner.Checked);
Debug.WriteLine(radChickenPark.Checked);
Debug.WriteLine(radChipsnSalsa.Checked);
Related
private void rateTextBox_TextChanged(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(pieceTextBox.Text))
{
}
else if (string.IsNullOrEmpty(rateReturnTextBox.Text))
{
}
else
{
int piece = Convert.ToInt32(pieceTextBox.Text);
int rate = Convert.ToInt32(rateTextBox.Text);
int netTotal = piece * rate;
netTotalBillTextBox.Text = netTotal.ToString();
}
}
//why dose not show the multiplication answer....where is the mistake?
I want this answer in netTotalBillTextBox .
Apparently, in the second condition shouldn't compare rateTextBox?
I assume it will always return string.Empty in rateReturnTextBox.
I'm trying to build a exam grader using C#. I'm new to this and don't know very much. What code would I use to add min and max buttons and to add a label stating whether it's a min or max?
private void btnAdd_Click(object sender, EventArgs e)
{
int points;
try
{
points = int.Parse(txtPoints.Text);
lstPoints.Items.Add(points);
txtPoints.Clear();
txtPoints.Focus();
if (lstPoints.Items.Count == 12)
{
txtPoints.Enabled = false;
btnAdd.Enabled = false;
}
if (lblResult.Text != "")
{
lblResult.Text = "";
}
}
catch
{
MessageBox.Show("Please enter only whole numbers");
txtPoints.Clear();
txtPoints.Focus();
}
}
private void btnAvg_Click(object sender, EventArgs e)
{
double total = 0;
for (int i = 0; i < lstPoints.Items.Count; i++)
{
total += (int)lstPoints.Items[i];
}
total /= lstPoints.Items.Count;
lblResult.Text = total.ToString();
}
private void btnClear_Click(object sender, EventArgs e)
{
lstPoints.Items.Clear();
txtPoints.Enabled = true;
btnAdd.Enabled = true;
}
}
}
hope this works
private void getMax()
{
int max=0;
for (int i = 0; i < lstPoints.Items.Count; i++)
{
if(max<(int)lstPoints.Items[i])
{
max=(int)lstPoints.Items[i];
}
}
lblResult.Text = max.ToString();
}
}
private void getMin()
{
int min=(int)lstPoints.Items[0];
for (int i = 1; i < lstPoints.Items.Count; i++)
{
if(min>(int)lstPoints.Items[i])
{
min=(int)lstPoints.Items[i];
}
}
lblResult.Text = min.ToString();
}
}
There are two possiblities as I see:
1) When you are writing this:
lstPoints.Items.Add(points);
Instead of adding to List(Of Integer) use SortedList. So the
list will always have the sorted result sets.
2) Use Array.Sort() to sort the records.
Once you have sorted records the first one is the minimum and the last one is the maximum (Assuming sorted in ascending order).
Take out two buttons and placed on the form, set Text Property from property window to Min and Max respectively and in event handler handle the Click event and pick the relevant resultset from lstPoints array.
Hope it helps!
I can't believe I got drained by this small problem trying to find the solution playing with the intellisense. No luck Just starting c# GUI. Just need a quick answer please.
if (listBox1.SelectedValue== "Chicken")
{
total += 15;
ord += " Chicken";
label4.Text = "chicken selected";
}
what the hell is wrong with this.
I want to execute the statements when the user selected the item "chicken" from listbox1.
public partial class Form1 : Form
{
double total = 0;
int x = 0;
string ord = "";
private void placeToolStripMenuItem_Click(object sender, EventArgs e)
{
checkBox1.Checked = false;
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
listBox1.SelectedItems.Clear();
if (checkBox1.Checked)
{
total += 1;
ord += " Water";
}
if (checkBox1.Text == "Extra Meat")
{
total += 1;
ord += ord+" Extra Meat ";
}
if (comboBox1.Text == "Extra Rice")
{
total += 1;
ord += " Extra Rice";
}
if (comboBox1.Text == "Extra Veggies")
{
total += 1;
ord +=" Extra Veggies";
}
if (listBox1.SelectedValue== "Chicken")
{
total+=15;
ord+=" Chicken";
label4.Text = "chicken selected";
}
if (listBox1.Text == "Pizza $8") //< my pathetic attempt to figure it out with intelisense
{
total+=8;
ord+="Pizza ";
label4.Text = "qwe";
}
if (listBox1.SelectedItem == "Spaghetti $12")//< my pathetic attempt to figure it out with intelisense
{
total+=12;
ord+=" Spaghetti";
}
if (listBox1.SelectedItem == "Fries $8")
{
total+=8;
ord+=" Fries";
}
if (listBox1.SelectedItem == "Burger $10")
{
total+=10;
ord+=" Burger";
}
//radiobutton
if (radioButton1.Checked)
{
total+=5;
ord += " Pineapple Juice";
}
if (radioButton2.Checked)
{
total+=6;
ord += " Mango Juice";
}
if (radioButton3.Checked)
{
total+=7;
ord += " Apple Juice";
}
if (radioButton4.Checked)
{
total+=8;
ord += " Orange Juice";
}
MessageBox.Show("Order Done");
}
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
ord = "";
total = 0;
}
private void displayToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Order: " + ord+"\nTotal: "+total);
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
}
You code cannot work, since you clear all the selections before you are processing the order. Move this code to the very end of the placeToolStripMenuItem_Click method:
// Process the order here ...
MessageBox.Show("Order Done");
checkBox1.Checked = false;
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
listBox1.SelectedItems.Clear();
I think that your approach is wrong. You should not have to make all these if-statements. Instead create a Product class
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public override ToString()
{
return String.Format("{0} ${1}", Name, Price);
}
}
Then add products to your listbox:
listbox1.Items.Add(new Product{ Name = "Chicken", Price = 15 });
listbox1.Items.Add(new Product{ Name = "Pizza", Price = 8 });
...
Then you can work with the selected item like this:
var product = listBox1.SelectedItem as Product;
if (product != null) {
total += product.Price;
ord += " " + product.Name;
label4.Text = product.Name + " selected";
}
Also declare total as decimal. Doubles are good for scientific calculations, but can easily yield results like 7.49999999 instead of 7.5. Decimals have been introduced especially for currency calculations. They are not very fast but they don't convert decimal numbers into binary numbers internally, instead the decimal digits are preserved. The problem with binary numbers is that for instance 1/10 cannot be represented accurately just like 1/3 cannot be represented accurately in the decimal system.
You can even add products to your radio buttons
radioButton3.Tag = new Product{ Name = "Apple Juice", Price = 7 };
A more advanced method would be to create your own radio button control with a Product property, but this solution will do it for now.
Then you can loop through all your radio buttons like this
foreach (var radioButton in Controls.OfType<RadioButton>()) {
if (radioButton.Checked) {
var p = (Product)radioButton.Tag;
total += p.Price;
ord += " " + p.Name;
}
}
You need to use SelectedItem.
if (listBox1.SelectedItem == "Chicken")
My program is throwing a Nullreferenceexception on me.
on this line:
if (listBox1.SelectedItem.ToString() == "Chicken $15")
I have to initialize it i guess but i have no idea how to initialize a listBox.
First Method:
if (listBox1.SelectedIndex != -1) //first check if any item is selected
if (listBox1.SelectedItem.ToString() == "Chicken")
Second Method:
if (listBox1.Text == "Chicken")
and just remove the line:
private void placeToolStripMenuItem_Click(object sender, EventArgs e)
{
listBox1.SelectedItems.Clear(); //remove this line
It clears your selected items, that's why you are not getting into any if condition.
So I have a label called lblScore.Text and lblScore.Text = iCorrectACount.ToString(); where iCorrectACount is basically a counter of how many questions a user answered right. Now what I want to do is basically make it so that this number multiplies the end score depending on the difficulty chosen i.e. if easy questions are chosen, multiply iCorrectACount by 0 and cast to string, if medium questions are chosen, multiply iCorrectACount by 1.5 and cast to string and if hard questions are chosen, multiply iCorrectACount by 2 and cast to string, but I'm not sure how I'd do this.
My code is like this:
private void QuizReset()
{
// Resets the difficulty selection control and shows it again upon resetting the quiz
difficultySelectionControl.Reset();
difficultySelectionControl.BringToFront();
// Disabled the 'Next' button and prompts the user to select a difficulty - User cannot continue without choosing
btnNext.Enabled = false;
lblStatus.Text = "Please select a difficulty";
// Sets the number of questions and correct answers to zero
iCorrectACount = 0;
iCurrentQIndex = 0;
}
private void LoadQuestions(Difficulty difficulty)
{
// Defines a random variable to be used to shuffle the order of the questions and answers
var rand = new Random();
// Loads the corresponding XML document with 'Easy', 'Medium' or 'Hard' questions depending on difficulty chosen
var xdoc = XDocument.Load(GetFileNameFor(difficulty));
// List of questions that are filtered from the XML file based on them being wrapped in question tags
_questions = xdoc.Descendants("question")
.Select(q => new Question()
{
ID = (int)q.Attribute("id"),
Difficulty = (int)q.Attribute("difficulty"),
QuestionText = (string)q.Element("text"),
Answers = q.Element("answers")
.Descendants()
// Stores all answers into a string
.Select(a => (string)a)
// Randomizing answers
.OrderBy(a => rand.Next())
.ToArray(),
CorrectAnswer = (string)q.Element("answers")
.Descendants("correctAnswer")
// Use value instead of index
.First()
})
// Selects questions that match the difficulty integer of the option the user chose
.Where(q => q.Difficulty == (int)difficulty + 1)
// Randomizing questions
.OrderBy(q => rand.Next())
.ToList();
lblStatus.Text = String.Format("There are {0} questions in this section", _questions.Count);
}
private string GetFileNameFor(Difficulty difficulty)
{
switch (difficulty)
{
case Difficulty.Easy: return "quiz_easy.xml";
case Difficulty.Medium: return "quiz_medium.xml";
case Difficulty.Hard: return "quiz_hard.xml";
default:
throw new ArgumentException();
}
}
private void PickQuestion()
{
questionControl.DisplayQuestion(_questions[iCurrentQIndex]);
questionControl.BringToFront();
iCurrentQIndex++;
}
private void FormMain_Load(object sender, EventArgs e)
{
QuizReset();
lblScore.Text = "0";
}
private void miNewQuiz_Click(object sender, EventArgs e)
{
QuizReset();
lblScore.Text = "0";
}
private void miExit_Click(object sender, EventArgs e)
{
Close();
}
private void miHelp_Click(object sender, EventArgs e)
{
FormHowToPlay form = new FormHowToPlay();
form.ShowDialog();
}
private void miAbout_Click(object sender, EventArgs e)
{
AboutBox1 aboutForm = new AboutBox1();
aboutForm.ShowDialog();
}
private void btnNext_Click(object sender, EventArgs e)
{
if (iCurrentQIndex < _questions.Count)
{
PickQuestion();
lblStatus.Text = String.Format("Question {0} of {1}", iCurrentQIndex, _questions.Count);
}
else
{
btnNext.Enabled = false;
lblStatus.Text = String.Format("You answered {0} questions correctly out of a possible {1}",
iCorrectACount, _questions.Count);
this.Hide();
SummaryForm sumForm = new SummaryForm();
DialogResult result = sumForm.ShowDialog();
MenuForm mnuform = new MenuForm();
mnuform.ShowDialog();
}
}
private void difficultySelectionControl_DifficultySelected(object sender, DifficultySelectedEventArgs e)
{
iCurrentQIndex = 0;
LoadQuestions(e.Difficulty);
btnNext.Enabled = true;
}
private void questionControl_QuestionAnswered(object sender, QuestionAnsweredEventArgs e)
{
if (e.IsCorrect)
iCorrectACount++;
lblScore.Text = iCorrectACount.ToString();
}
It's the last little thing I need to figure out and I can't figure out how to get it so that if the difficulty = easy/medium/hard, multiply iCorrectAmount by 1/1.5/2/0.
Thanks for any help or advice.
Just do this:
int modifier = 1;
if (difficulty == Difficulty.Medium) { modifier = 1.5; }
if (difficulty == Difficulty.Hard) { modifier = 2; }
lblScore.Text = (iCorrectACount * modifier).ToString();
you'll need to get the difficulty from somewhere obviously, and I can't tell where exactly right now, but you have it because you passed it into the method LoadQuestions and GetFileNameFor, so just grab it, run the code, and BAM you got your modifier.
NOTE: I set the modifier to 1 by default, I'm pretty sure you didn't want to set it to 0 since that would net 0 as the result every time.
in difficultySelectionControl_DifficultySelected, store the selected difficulty in a class variable, m_difficulty.
Then, just access it in questionControl_QuestionAnswered
in your class definition, add private Difficulty m_difficulty.
in difficultySelectionControl_DifficultySelected, add a line saying m_difficulty = e.Difficulty.
then, you can use that difficulty in your questionControl_QuestionAnswered, just like #Michael Perrenoud suggested.
I'm new to C# so still finding my way around.
I have a button I want to enable only when a user enter text to textbox.
I get this error - "Object reference not set to an instance of an object".
Here is the related code (without the using and variables):
public MainWindow()
{
MessageBox.Show("Make sure to edit Settings tab.");
InitializeComponent();
if (startTextBox.Text == "0") // Checks to see if a textbox has some text other than zero. if no than the user cannot press button1 yet.
{
button1.IsEnabled = false;
}
else
{
button1.IsEnabled = true;
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (radioButton1.IsChecked == false)
{
label17.Content = "No Hourly wage was set.";
}
}
private void add(object sender, RoutedEventArgs e) /// here is a very long method so I've removed its content.
}
public void printTime()
{
int Sum = (this.EndInt - this.StartInt);
int Money = (Sum * this.L1001);
label16.Content = Sum;
label17.Content = Money;
if ((textBox1.Text == "0") && ((textBox2.Text == "0") || (textBox3.Text == "0")))
{
label17.Content = "No Hourly wage was set.";
}
}
public void printTime2()
{
int Sum = (this.EndInt - this.StartInt);
MessageBox.Show("Is it possible that you've worked - " + Sum + " Hours?");
}
public void printTime3()
{
int Sum = (this.EndInt - this.StartInt);
int Money = (Sum * this.L1001);
label16.Content = Sum;
label17.Content = Money;
if (textBox1.Text == "0")
{
label17.Content = "No Hourly wage was set.";
}
}
public int Convert(String S)
{
int i = int.Parse(S);
return i;
}
// Input Validation For Excepting Integers Only!
private void input(object sender, TextCompositionEventArgs e)
{ CheckIsNumeric(e); }
private void CheckIsNumeric(TextCompositionEventArgs e)
{
int result; if (!(int.TryParse(e.Text, out result) || e.Text == "."))
{ e.Handled = true; MessageBox.Show("Numbers Only"); }
}
private void startTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
button1.IsEnabled = true;
}
}
}
It's the scope problem. You didn't show where button1 is defined. But inside your event handler startTextBox_TextChanged, button1 definition is nowhere to be found (actually it needs to be instantiated as well). Since you try to invoke a method on an object (button1) which has not been instantiated yet, that exception was thrown.
If you post more than just those snippets, either I or someone else might be able to further help you.