Reputation: 73
The following problem though I can not seem to solve by using google.
The program I am writing ask for an amount of shoes that are going to be purchased, then based on amount of shoes a discount is given, 0%, 15%, or 25%.
I have it all written so that the right price appears in a label, the only thing I need to do is make the according radiobutton check itself ( 0%, 15%, or 25%)
Can somebody tell me the syntax?
Code I have written thus far:
private void button1_Click(object sender, EventArgs e)
{
decimal schoenen1= 0;
schoenen1 = Convert.ToDecimal(textBox1.Text);
decimal prijs1 = schoenen1 * 100;
decimal prijs2 = schoenen1 * 85;
decimal prijs3 = schoenen1 * 75;
if (schoenen1 >5)
{
label3.Text = prijs3.ToString();
}
if (schoenen1 == 2)
{
label3.Text = prijs2.ToString();
}
if (schoenen1 >2)
{
label3.Text = prijs2.ToString();
}
if (schoenen1 == 1)
{
label3.Text = prijs1.ToString();
}
Upvotes: 0
Views: 50
Reputation: 112437
Since you want to assign the label only once, use if-else, otherwise e.g. when schoenen1 = 6
then case > 5 and case > 2 will both be executed.
private void button1_Click(object sender, EventArgs e)
{
decimal schoenen1 = Convert.ToDecimal(textBox1.Text);
decimal prijs1 = schoenen1 * 100;
decimal prijs2 = schoenen1 * 85;
decimal prijs3 = schoenen1 * 75;
if (schoenen1 > 5) {
label3.Text = prijs3.ToString();
radioButton1.Checked = true;
} else if (schoenen1 >= 2) {
label3.Text = prijs2.ToString();
radioButton2.Checked = true;
} else if (schoenen1 == 1) {
label3.Text = prijs1.ToString();
radioButton3.Checked = true;
}
}
Also, you can combine schoenen1 == 2
and schoenen1 > 2
into schoenen1 >= 2
, since you are assigning the same value in both cases.
Alternatively, you can exit the method with return
:
private void button1_Click(object sender, EventArgs e)
{
decimal schoenen1 = Convert.ToDecimal(textBox1.Text);
decimal prijs1 = schoenen1 * 100;
decimal prijs2 = schoenen1 * 85;
decimal prijs3 = schoenen1 * 75;
if (schoenen1 > 5) {
label3.Text = prijs3.ToString();
radioButton1.Checked = true;
return;
}
if (schoenen1 >= 2) {
label3.Text = prijs2.ToString();
radioButton2.Checked = true;
return;
}
if (schoenen1 == 1) {
label3.Text = prijs1.ToString();
radioButton3.Checked = true;
}
}
Yet another way is to use a switch statement:
switch (schoenen1)
{
case > 5:
label3.Text = prijs3.ToString();
radioButton1.Checked = true;
break;
case >= 2:
label3.Text = prijs2.ToString();
radioButton2.Checked = true;
break;
case 1:
label3.Text = prijs1.ToString();
radioButton3.Checked = true;
break;
}
See also: Selection statements - if, else and switch
Upvotes: 1