Tom*_*Tom 3 asp.net string null
我已经研究了一段时间了,而我却错过了显而易见的事情.我正在尝试确保如果文本框值保留为空,则不会抛出错误,而是在文本框中显示一条简单的消息.然而,我所得到的以及我尝试过类似的其他几种方法都没有用.我无法弄清楚为什么这不起作用以及我需要采取哪些不同的做法.
基本:
这是一个简单的计算器,允许人们进入他们的腰部,颈部和身高测量值,以用于计算他们估计的体脂百分比的公式.除非字段留空,否则计算将正常工作.
谢谢你的帮助!
我的代码:
        if (TBWaist.Text == null || TBNeck.Text == null || TBHeight.Text == null)
        {
            TBBodyFat.Text = "Value missing";
        }
        else
            if (TBWaist.Text != null & TBNeck.Text != null & TBHeight.Text != null)
            {
                double waist;
                double neck;
                double height;
                waist = Convert.ToDouble(TBWaist.Text);
                neck = Convert.ToDouble(TBNeck.Text);
                height = Convert.ToDouble(TBHeight.Text);
                TBBodyFat.Text = Convert.ToString(String.Format("{0:p2}", ((501.5 / (1.0324 - .19077 * (Math.Log10(waist - neck)) + .15456 * (Math.Log10(height))) - 450) / 100)));
Run Code Online (Sandbox Code Playgroud)
错误信息
如果我将腰部文本框留空,这是我收到的错误消息.如果我将其他任何一个留空,我也会得到同样的错误.
第45行的输入字符串格式不正确.
waist = Convert.ToDouble(TBWaist.Text);
Run Code Online (Sandbox Code Playgroud)
    我建议使用TryParse方法.通过这种方式,空白,空字符串或不可转换为字符串的内容都被视为相同.其次,我建议将RequiredFieldValidators和/或RegularExpressionValidators添加到每个文本框中,以确保用户输入值并且该值是数字.通过这种方式,事件过程中的检查将作为最后的沟渠检查,而不是要求PostBack进行验证
protected void Button1_Click(object sender, EventArgs e)
{
    //Navy Men's Body Fat Formula:  %Fat=495/(1.0324-.19077(log(abdomen-neck))+.15456(log(height)))-450 
    //string outputString = String.Format("At loop position {0}.\n", i);
    double waist;
    double neck;
    double height;
    if ( !double.TryParse( TBWaist.Text, out waist )
        || !double.TryParse( TBNeck.Text, out neck )
        || !double.TryParse( TBHeight.Text, out height ) )
    {
        ErrorMessageLabel.Text = "Please ensure that each value entered is numeric.";
        return;
    }   
    var bodyFat = (501.5 
        / (1.0324 - .19077 * (Math.Log10(waist - neck)) 
            + .15456 * (Math.Log10(height))
            ) - 450 ) / 100;
    TBBodyFat.Text = bodyFat.ToString("P2");
}
Run Code Online (Sandbox Code Playgroud)