标签不会改变 [英] The label doesn't change

查看:85
本文介绍了标签不会改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 I wrote a code in c# windows form application contain many if statement when I run project and enter data the label should change its color according to the if clause, but the color is still as in the last label  





我尝试过:





What I have tried:

private void button1_Click(object sender, EventArgs e)
        {
            double height, weight;
            double BMI = 0;
            height = Convert.ToDouble(textBox1.Text);
            weight = Convert.ToDouble(textBox2.Text);


            BMI = weight / (height * height);
            if (BMI < 18.5)
            {
                label3.Text = Convert.ToString("Under Weight");
                label3.ForeColor = Color.Blue; }

            else if
                ((BMI > 18.5) && (BMI < 24.9))
            {    label3.Text = Convert.ToString("Normal");
                label3.ForeColor = Color.Black;
            }
           else if        ((BMI > 25) && (BMI < 29.9))
                
             {       label3.Text = Convert.ToString("Over Weight");
                     label3.BackColor = System.Drawing.Color.Green;
                     label3.ForeColor = Color.White;
            } 

            else if (BMI >= 30)
                    label3.Text = Convert.ToString("Obese");
                label3.ForeColor = Color.Red;
        }

推荐答案

我认为你的if条款与BMI值不符。

- BMI == 18.5

- 24.9< = BMI&& BMI< = 25

- 29.9< = BMI&& BMI< 30



以下代码将匹配任何BMI值。

I think your if clauses don't match below BMI value.
- BMI == 18.5
- 24.9 <= BMI && BMI <= 25
- 29.9 <= BMI && BMI < 30

Below code will be match any BMI value.
if (BMI < 18.5)
{
    // Under Weight
}
else if (BMI < 25)
{
    // Normal
}
else if (BMI < 30)
{
    // Over Weight
}
else
{
    // Obese
}


对于初学者,不要将Convert方法与用户输入一起使用 - 如果他们输入的值没有'如果匹配正确的格式,您的应用程序将崩溃。请改用TryParse方法:

For starters, don't use Convert methods with user input - if the value they enter doesn't match the right format, your application will crash. Use the TryParse methods instead:
double height, weight;
double BMI = 0;
if (!double.TryParse(textBox1.Text, out height))
    {
    MessageBox.Show(


\{ textBox1.Text} \不是有效的高度);
return ;
}
if (!double.TryParse(textBox2.Text, out weight) ))
{
MessageBox.Show(
"\"{textBox1.Text}\" is not a valid height"); return; } if (!double.TryParse(textBox2.Text, out weight)) { MessageBox.Show(


这篇关于标签不会改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆