gpt4 book ai didi

asp.net - 检查字段值是否为空

转载 作者:行者123 更新时间:2023-12-02 12:02:57 25 4
gpt4 key购买 nike

我已经研究这个问题有一段时间了,但我错过了显而易见的事情。我试图确保如果文本框值留空,则不会引发错误,而是在文本框中显示一条简单的消息。然而,我所拥有的以及我尝试过的其他几种与此类似的方法都没有奏效。我不明白为什么这不起作用以及我需要采取什么不同的措施。

基础知识:

这是一个简单的计算器,允许输入腰围、颈部和高度测量值,用于计算估计 body 脂肪百分比的公式。除非字段留空,否则计算将正常进行。

感谢您的帮助!

我的代码:

        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)));

错误消息

这是如果我将腰部文本框留空时收到的错误消息。如果我也将其他任何一个留空,我会得到同样的错误。

Input string was not in a correct format on line 45.

waist = Convert.ToDouble(TBWaist.Text);

最佳答案

我建议使用 TryParse 方法。这样,空白、空字符串或不可转换为字符串的内容都被视为相同。其次,我建议将RequiredFieldValidators 和/或RegularExpressionValidators 添加到每个文本框,以确保用户输入一个值并且该值是数字。这样,事件过程中的检查将充当最后的检查,而不需要回发进行验证

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");
}

关于asp.net - 检查字段值是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3436243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com