你在按钮事件中有一个if语句,当我运行代码并选择第一个收音机并单击按钮(进行计算)时,它会在标签上打印出来,但是当我点击时第二个单选按钮,然后单击按钮来计算答案根本没有任何反应。有任何想法
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
double a; // have to declare double here as we cannot include it below as bool is a rue or false statment
bool success1 = double.TryParse(textBox1.Text, out a); // take in value as true or false
if (success1) // check if it was parsed successful
{
label4.Text = ConvertToCel(a).ToString(); // now set it in label
}
else if (radioButton1.Checked == false && radioButton2.Checked == true)
{
double a1;
bool success = double.TryParse(textBox1.Text, out a1);
if (success){
label3.Text = ConvertToFar(a1).ToString();
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == false)
{
label4.Text = "Please select an option from above";
}
}
}�
答案 0 :(得分:2)
问题是您正在检查首先检查radiobutton1的条件,然后在其中嵌套其他条件,因此如果第一个条件为false,则不检查其他条件,以避免您应该带另一个否则if条件超出第一个if条件,你可以使用: -
private void button1_Click(object sender, EventArgs e)
{
double a; // have to declare double here as we cannot include it below as bool is a rue or false statment
bool success1 = double.TryParse(textBox1.Text, out a); // take in value as true or false
if (radioButton1.Checked == true)
{
if (success1) // check if it was parsed successful
{
label4.Text = ConvertToCel(a).ToString(); // now set it in label
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == true)
{
if (success)
{
label3.Text = ConvertToFar(a).ToString();
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == false)
{
label4.Text = "Please select an option from above";
}
}
答案 1 :(得分:1)
这是因为单选按钮是互斥的,如果选中radioButton1
,则只执行代码。您可能还应该处理无法正确解析文本框的情况(即,如果用户输入的内容无法转换为double)。我已将其包括在内。
double a;
bool success = double.TryParse(textBox1.Text, out a);
if (success)
{
if (radioButton1.Checked == true)
{
label4.Text = ConvertToCel(a).ToString();
}
else if (radioButton2.Checked == true)
{
label3.Text = ConvertToFar(a).ToString();
}
else
{
label4.Text = "Please select an option from above";
}
}
else
{
label4.Text = "The value could not be convered to a number.";
}
答案 2 :(得分:0)
那是因为您已将else
放在第一个if
语句中的if
语句中。只有当第一个if
语句中的条件为真时,才会运行对radiobutton 2的检查。
在if
语句之前结束第一个else
语句的块:
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
double a; // have to declare double here as we cannot include it below as bool is a rue or false statment
bool success1 = double.TryParse(textBox1.Text, out a); // take in value as true or false
if (success1) // check if it was parsed successful
{
label4.Text = ConvertToCel(a).ToString(); // now set it in label
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == true)
{
double a1;
bool success = double.TryParse(textBox1.Text, out a1);
if (success){
label3.Text = ConvertToFar(a1).ToString();
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == false)
{
label4.Text = "Please select an option from above";
}
}