How to change value of label depending on criteria - c#

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.

Related

How to force compiler not to consider any block of code if it comes from different button event

In my case, I don't want this block:if (Clicked == true){i = i+2;} and if (Clicked == false){i = i-2;}to work if compiler comes inside of different particular button ;
This is Button2 which returns elements of a sequence for a brand name given as
textBox4.
bool Clicked = false;
private void button2_Click(object sender, EventArgs e)
{
var car = cars.FirstOrDefault(c => c.Brand == textBox4.Text);
i = cars.FindIndex(c => c.Brand == textBox4.Text);
if (car != null)
{
label1.Text = car.Brand;
label2.Text = car.Model;
label3.Text = car.Color;
i++;
}
else
{
MessageBox.Show("This car is not in the list");
}
}
And button3_click event should display next elements of the sequence.
private void button3_Click(object sender, EventArgs e)
{
var car = cars.Select(a => a);
if (Clicked == true)
{
i=i+2;
}
if (i >= 0&&i < cars.Count)
{
label1.Text = car.ToArray()[i].Brand;
label2.Text = car.ToArray()[i].Model;
label3.Text = car.ToArray()[i].Color;
i++; //abc; i = 1;
Clicked = false;
}
}
And Button4 displays the previous elements of a sequence
private void button4_Click(object sender, EventArgs e)
{
if (Clicked == false)
{
i=i-2;
Clicked = true;
}
var car = cars.Select(a => a);
if (i >= 0&&i<=cars.Count)
{
label1.Text = car.ToArray()[i].Brand;
label2.Text = car.ToArray()[i].Model;
label3.Text = car.ToArray()[i].Color;
i--;
}
}
I don't want this :if (Clicked == true){i = i+2;} and this :if (Clicked == false) {i=i-2;} block of codes in the button3 and button4 (next and prev buttons) to run whenever I hit any one of them right after the codes inside of button2 have been worked. I couldn't work it out using bool flags as there're three cases needed to be considered. How to deal with it?
I'm going to try to answer this, not 100% sure exactly what you're asking...
My assumption is that you don't want the "if(Clicked..." part to run if you've just previously clicked button2, but after clicking either button3 or button4, it's fine to run the if statement.
Trying to figure out your code, I think you can shrink it way down to remove those. First, the i++ should be removed from button2_Click
private void button2_Click(object sender, EventArgs e)
{
i = cars.FindIndex(c => c.Brand == textBox4.Text);
if(i >= 0)
{
var car = cars.ToArray()[i]; // no reason to search twice
label1.Text = car.Brand;
label2.Text = car.Model;
label3.Text = car.Color;
}
else
{
MessageBox.Show("This car is not in the list");
}
}
Since the index "i" is not changed in button2_Click, it can be changed in the "next" and "previous" buttons before it's indexed.
private void button3_Click(object sender, EventArgs e)
{
// I don't think you need this
// var car = cars.Select(a => a);
if (i + 1 >= 0 && i + 1 < cars.Count)
{
i++;
var car = cars.ToArray()[i];
label1.Text = car.Brand;
label2.Text = car.Model;
label3.Text = car.Color;
}
}
private void button4_Click(object sender, EventArgs e)
{
if (i - 1 >= 0 && i - 1 <= cars.Count)
{
i--;
var car = cars.ToArray()[i];
label1.Text = car.Brand;
label2.Text = car.Model;
label3.Text = car.Color;
}
}
Since both button3_Click and button4_Click are almost identical, you could probably put them in a single event and check which button is pressed and increment/decrement as needed, but that's an opinion call, there are reasons not to do that as well.
I don't know what type "cars" is, but it may even be better to make a member variable to hold cars.ToArray() so ToArray doesn't have to be called so many times.

Index Out Of Range exception on " examScores[countOfExams] = double.Parse(examScoresTextBox.Text);" [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 6 years ago.
When I press the click event to add array values, it gives me an out of index exception error. I'd like to know why it's happening and how to fix it, thanks.
using System;
using System.Windows.Forms;
namespace ArrayTestCalculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double total = 0;
double average = 0;
double scoreInput = 0;
int countOfExams = 0;
double[] examScores;
double count = 0;
//field array declare
private void enterBtn_Click(object sender, EventArgs e)
{
countOfExams = int.Parse(numOfExamsTextBox.Text);
examScores = new double[countOfExams];
examLabel.Text = "Exam 1: ";
label1.Visible = false;
numOfExamsTextBox.Visible = false;
enterBtn.Visible = false;
examLabel.Visible = true;
examScoresTextBox.Visible = true;
addBtn.Visible = true;
}
private void addBtn_Click(object sender, EventArgs e)
{
examLabel.Text = "Exam " + (countOfExams +1) + ":";
examScores[countOfExams] = double.Parse(examScoresTextBox.Text);
countOfExams++;
examScoresTextBox.ResetText();
examScoresTextBox.Focus();
if(countOfExams >= examScores.Length)
{
MessageBox.Show("hoise vaya");
}
}
private void clearBtn_Click(object sender, EventArgs e)
{
Array.Clear(examScores, 0, examScores.Length);
ClearAll();
}
private void exitBtn_Click(object sender, EventArgs e)
{
this.Close();
}
public void ClearAll()
{
examLabel.Text = "Exam:";
examScoresTextBox.ResetText();
numOfExamsTextBox.ResetText();
}
private void calcBtn_Click(object sender, EventArgs e)
{
}
}
}
In the first line of your enterBtn_Click,
countOfExams = int.Parse(numOfExamsTextBox.Text);
I suppose you are using countOfExams as the total length of the array.
Later in the second line of your addBtn_Click,
examScores[countOfExams] = double.Parse(examScoresTextBox.Text);
countOfExams++;
I suppose you are using countOfExams to track the actual number of exams. Because countOfExams is already set to the length, it results in OutOfRangeException.
Thus, I suggest you to use another variable (e.g. a local variable) for the total length of the array,
var size = int.Parse(numOfExamsTextBox.Text);
examScores = new double[size];
double[] examScores; has been defined as array, which was never initialized if you are not calling enterBtn_Click first
Ideally,
You should first initialize/ check if it is initialized it by
double[] examScores = new double[<length>];
also, the counter starts from 0 and not 1
If you are not sure about the length or capacity, use List

Display a string variable in a textbox

I am currently doing a simili-HangMan project. As I looked through many other projects up here, I haven't found what I was looking for exactly.
Notes:
* The variable motRechercher is the randomized word.
* It can be used everywhere - I did a get set for it.
MY QUESTION IS: I want to display a string in a textbox that is a random word selected from a list, how do I do that?
Here's my code for the textbox:
private void txtMot_TextChanged(object sender, TextChangedEventArgs e)
{
for (int i = 0; i <= motRechercher.Length; i++)
{
StringBuilder sb = new StringBuilder(motRechercher);
sb[i] = '_';
string sba = sb.ToString();
txtMot.Text=sba;
}
}
If the word is for an example : Cat. It should display: _ _ _
Here's my code for the random word selector (It works) - It's mostly to give an idea:
private void btnDemarrer_Click(object sender, RoutedEventArgs e)
{
Random rdn = new Random();
int nbreAleatoire = rdn.Next(0, 27);
motRechercher = lesMots[nbreAleatoire];
}
If you have any questions regarding my code I'll edit it to make it easier for you to understand/help me.
instead of
private void txtMot_TextChanged(object sender, TextChangedEventArgs e)
{
for (int i = 0; i <= motRechercher.Length; i++)
{
StringBuilder sb = new StringBuilder(motRechercher);
sb[i] = '_';
string sba = sb.ToString();
txtMot.Text=sba;
}
}
add another button for next random no to populate to text box.
inside button click do this which will check the length and get the data for you:
private void btnNext_Click(object sender, RoutedEventArgs e)
{
if(motRechercher.Length > 0)
{
String str = new String('_', motRechercher.Length);
txtMot.Text = str;
}
}
If I understand the question, this might be what you're after:
bool changing = false; // variable in class-scope
private void txtMot_TextChanged(object sender, TextChangedEventArgs e)
{
if (changing == false)
{
try
{
changing = true;
String str = new String('_', motRechercher.Length);
txtMot.Text = str;
}
finally
{
changing = false;
}
}
}

Randomly access string from array list

I am working on a quiz project which also allows user to add new questions.
I have an array list in which questions are stored and retrieved for displaying. Each object saved in the array list contains 5 strings.
Question
Right answer
Wrong answer 1
Wrong answer 2
Wrong answer 3
How can I randomly select objects from the array list to be displayed on the screen? And how can I shuffle the 4 answers (as radio buttons) so that the right answer appears at different positions each time?
namespace quiz
{
public partial class Quiz : Form
{
private ArrayList Questionslist;
public Quiz(ArrayList list)
{
InitializeComponent();
Questionslist = list;
}
int index = 0;
private void Quiz_Load(object sender, EventArgs e)
{
//creating an object of class Question and copying the object at index1 from arraylist into it
Question q = (Question)Questionslist[index];
//to display the contents
lblQs.Text = q.Quest;
radioButtonA1.Text = q.RightAnswer;
radioButtonA2.Text = q.WrongAnswer1;
radioButtonA3.Text = q.WrongAnswer2;
radioButtonA4.Text = q.WrongAnswer3;
}
private int Score = 0;
private void radioButtonA1_CheckedChanged(object sender, EventArgs e)
{
//if checkbox is checked
//displaying text in separate two lines on messagebox
if (radioButtonA1.Checked == true)
{
MessageBox.Show("Well Done" + Environment.NewLine + "You Are Right");
Score++;
index++;
if (index < Questionslist.Count)
{
radioButtonA1.Checked = false;
radioButtonA2.Checked = false;
radioButtonA3.Checked = false;
radioButtonA4.Checked = false;
Quiz_Load(sender, e);
}
else
{
index--;
MessageBox.Show("Quiz Finished" + Environment.NewLine + "your Score is" + Score);
Close();
}
}
}
private void radioButtonA2_CheckedChanged(object sender, EventArgs e)
{
if (radioButtonA2.Checked == true)
{
MessageBox.Show("Sorry" + Environment.NewLine + "You Are Wrong");
Close();
}
}
private void radioButtonA3_CheckedChanged(object sender, EventArgs e)
{
if (radioButtonA3.Checked == true)
{
MessageBox.Show("Sorry" + Environment.NewLine + "You Are Wrong");
Close();
}
}
private void radioButtonA4_CheckedChanged(object sender, EventArgs e)
{
if (radioButtonA4.Checked == true)
{
MessageBox.Show("Sorry" + Environment.NewLine + "You Are Wrong");
Close();
}
}
}
}
this is the code for class question
namespace quiz
{
[Serializable()]
public class Question : ISerializable
{
public String Quest;
public String RightAnswer;
public String WrongAnswer1;
public String WrongAnswer2;
public String WrongAnswer3;
public Question()
{
Quest = null;
RightAnswer=null;
WrongAnswer1=null;
WrongAnswer2=null;
WrongAnswer3=null;
}
//serialization function
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Question", Quest);
info.AddValue("Right Answer", RightAnswer);
info.AddValue("WrongAnswer1",WrongAnswer1);
info.AddValue("WrongAnswer2",WrongAnswer2);
info.AddValue("WrongAnswer3",WrongAnswer3);
}
//deserializaton constructor
public Question(SerializationInfo info, StreamingContext context)
{
Quest = (String)info.GetValue("Question", typeof(String));
RightAnswer=(String)info.GetValue("Right Answer",typeof(String));
WrongAnswer1=(String)info.GetValue("WrongAnswer1",typeof(String));
WrongAnswer2=(String)info.GetValue("WrongAnswer2",typeof(String));
WrongAnswer3=(String)info.GetValue("WrongAnswer3",typeof(String));
}
}
}
You know which one is the 'right' answer based on the Text property. One approach would be to store the answers in an array and shuffle the array before assigning it to the radio buttons:
// You're going to make questionList a List<Question> because if you like
// Right answers you know that ArrayList is Wrong.
Question q = questionList[index];
// You should move this next bit to the Question class
string[] answers = new string[]
{
q.RightAnswer,
q.WrongAnswer1,
q.WrongAnswer2,
q.WrongAnswer3
};
// Using the Fisher-Yates shuffle from:
// http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp
Shuffle(answers);
// Ideally: question.GetShuffledAnswers()
radioButtonA1.Text = answers[0];
radioButtonA2.Text = answers[1];
radioButtonA3.Text = answers[2];
radioButtonA4.Text = answers[3];
Then later, all you need is a single radio button event handler that they all share:
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = (RadioButton)sender;
Question q = questionList[index];
//if checkbox is checked
//displaying text in separate two lines on messagebox
if (rb.Checked && q.RightAnswer == rb.Text)
{
// Move your code to another method
// MessageBox.Show("Well Done" + Environment.NewLine + "You Are Right");
UserSelectedCorrectAnswer();
}
else if (rb.Checked)
{
// They checked the radio button, but were wrong!
// MessageBox.Show("Sorry" + Environment.NewLine + "You Are Wrong");
UserSelectedWrongAnswer();
}
}
Pick a random string from ArrayList:
string randomPick(ArrayList strings)
{
return strings[random.Next(strings.Length)];
}
You might consider having a Question class. That would contain a string Text member for the question (because I think Question.Question is silly, Question.Text makes more sense when read). Since you mentioned an ArrayList (not because I think it's the best solution), you can have one of those as a member as well which would contain all the potential answers.
When you create a question, you can display Question.Text, then use the function above to randomly pick an answer. Then use RemoveAt(index) on the answers to ensure you don't duplicate answers.
I'd make a Question class containing the question, the right answer and a list of possible answers, and have methods that return the possible answers in randomized order and compares a guess to the correct answer. It could look something like this:
class Question
{
String question;
String rightAnswer;
List<String> possibleAnswers = new ArrayList<String>();
public Question(String question, String answer, List<String> possibleAnswers)
{
this.question = question;
this.rightAnswer = answer;
this.possibleAnswers.addAll(possibleAnswers);
this.possibleAnswers.add(this.rightAnswer);
}
public List<String> getAnswers()
{
Collections.shuffle(possibleAnswers);
return possibleAnswers;
}
public boolean isCorrect(String answer)
{
return answer.equals(correctAnswer);
}
}
You should encapsulate all the questions in a class. For example, create a class named Question. This class can contain 5 variables: String question, String answer1, String answer2, String answer3 and String answer4.
Save all your questions in a database or read them from a file and load them on the start of the program.
Use the Random class to randomly select a question and to 'shuffle' the 4 questions.
Here's a method that will work:
public List<string> Randomize(string[] numbers)
{
List<string> randomized = new List<string>();
List<string> original = new List<string>(numbers);
Random r = new Random();
while (original.Count > 0) {
int index = r.Next(original.Count);
randomized.Add(original[index]);
original.RemoveAt(index);
}
return randomized;
}
just adapt it to string array instead of int array
The shuffle is probably a standard question, but I guess this will work:
// Warning: Not a thread-safe type.
// Will be corrupted if application is multi-threaded.
static readonly Random randomNumberGenerator = new Random();
// Returns a new sequence whose elements are
// the elements of 'inputListOrArray' in random order
public static IEnumerable<T> Shuffle<T>(IReadOnlyList<T> inputListOrArray)
{
return GetPermutation(inputListOrArray.Count).Select(x => inputListOrArray[x]);
}
static IEnumerable<int> GetPermutation(int n)
{
var list = Enumerable.Range(0, n).ToArray();
for (int idx = 0; idx < n; ++idx)
{
int swapWith = randomNumberGenerator.Next(idx, n);
yield return list[swapWith];
list[swapWith] = list[idx];
}
}
If you don't have IReadOnlyList<T> (.NET 4.5), just use IList<T>. The incoming object is not mutated.
thanks to all of u who answered my question.i did it this way.
private void Quiz_Load(object sender, EventArgs e)
{
displayQs();
}
private void displayQs()
{
Random _random = new Random();
int z = _random.Next(Questions.Count);
Question q = (Question)Questions[z];
Qslbl.Text = q.Quest;
DisplayAns(q, _random);
}
private void DisplayAns(Question q, Random _random)
{
int j = 0;
int[] array = new int[4];
for (int i = 0; j <= 3; i++)
{
int x = _random.Next(4);
x++;
if (array.Contains(x))
{
continue;
}
else
{
array[j] = x;
j++;
string answer = null;
if (j == 1)
answer = q.RightAnswer;
else if (j == 2)
answer = q.WrongAnswer1;
else if (j == 3)
answer = q.WrongAnswer2;
else if (j == 4)
answer = q.WrongAnswer3;
if (x == 1)
radioButton1.Text = answer;
else if (x == 2)
radioButton2.Text = answer;
else if (x == 3)
radioButton3.Text = answer;
else if (x == 4)
radioButton4.Text = answer;
}
}
}

Output label shows only part of what I want to display

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);

Categories

Resources