单选按钮窗口无法正常工作

时间:2018-04-09 08:47:21

标签: c# windows-forms-designer

我已经使用3个单选按钮实现了c#代码,但它无法正常工作:

enter image description here

它只显示第一个和第二个,但没有显示最后一个。我尝试使用发送方对象,但它没有用。

代码:

private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
    if (radioButton1.Checked == true)
    {
        double Weight2 = Convert.ToDouble(textBox1.Text);
        double LowW = Weight2 * 24 * 1.2;
        String s = Convert.ToString(LowW);
        richTextBox1.Text = "The calories per day for low actaivity is : " + s;
    }
    else if (radioButton2.Checked == true)
    {
        double Weight2 = Convert.ToDouble(textBox1.Text);
        double LowW = Weight2 * 24 * 1.3;
        String s = Convert.ToString(LowW);
        richTextBox1.Text = "The calories per day for low actaivity is : " + s;
    }
        else if (radioButton3.Checked == true)
        {
            double Weight2 = Convert.ToDouble(textBox1.Text);
            double LowW = Weight2 * 24 * 1.4;
            String s = Convert.ToString(LowW);
           richTextBox1.Text = "The calories per day for low actaivity is : " + s;

        }
    }

1 个答案:

答案 0 :(得分:0)

如果你的radiobutton1是唯一一个带代码的人,我只能重现你的行为。为什么会这样......代码在更改选中的值时运行

  • 当您选择radiobutton1时会触发。

  • 当你选择2或3时,它会触发,因为它现在变为未被选中,让我们假装你选择2。

  • 但是,如果你选择3,则radiobutton1的值没有改变,所以代码不会触发。

作为一个例子。我将代码最小化,将其分配给所有3个按钮并得到了这个:

    if (radioButton1.Checked == true)
    {
        textBox1.Text = "The calories per day for low activity is : x";
    }
    else if (radioButton2.Checked == true)
    {
        textBox1.Text = "The calories per day for med activity is : x";
    }
    else if (radioButton3.Checked == true)
    {
        textBox1.Text = "The calories per day for hi activity is : x";
    }
    Text = "checked " + (sender as RadioButton).Name;

最后一次显示“发件人”是调用例程的按钮。这样我才能检查。现在,本质上这个代码是低效的,因为理论上一旦选择了一个项目,你就改变了它 - 代码实际上被调用了两次。

虽然这是一个非常低成本的东西 - 这是值得注意的事情。您可以通过检查发件人来缓解这种情况,但是如果它是一个单选按钮来检查已检查的值是否为真,然后继续执行您的代码