验证文本框我在双数据类型中有价值 [英] Validate Textboxes And I Have Value In Double Data Type

查看:79
本文介绍了验证文本框我在双数据类型中有价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文本框,我想从用户拿取金额和人数并分配金额/人并将结果转换为双

这里是我的代码但它会给我错误,这是我的代码及以下是错误代码

I have a two text boxes and i want to take amount and person from user and divide amount/person and convert result into double
here is my code but it will give me error, Here is my code and below is the erro code

protected void btnSearch_Click(object sender, EventArgs e)
{
if((txtAmount.Text == "") || (txtPerson.Text == ""))
{
Response.Write("please enter amount");
} 
else
{
double amount = int.Parse(txtAmount.Text);
double persons = int.Parse(txtPerson.Text);
double result = amount / persons;
d.Price = Convert.ToInt32(result);
d.Select(d);
Display();
}







Line 39:             else
Line 40:             {
Line 41:                 double amount = int.Parse(txtAmount.Text);
Line 42:                 double persons = int.Parse(txtPerson.Text);
Line 43:                 double result = amount / persons;

推荐答案

Repalce

Repalce
double amount = int.Parse(txtAmount.Text);
double persons = int.Parse(txtPerson.Text);



使用


With

double amount = Double.Parse(txtAmount.Text);
double persons = Double.Parse(txtPerson.Text);



这可能有所帮助。


This may help.


我认为你的代码没有正确验证输入值。



I think your code does not validate input values properly.

if((txtAmount.Text == "") || (txtPerson.Text == ""))
{
    Response.Write("please enter amount");
}





仅适用于或String.Empty。那个(一个空间)怎么样?



那么无效值(NaN - 不是数值)怎么样?您应修改此代码以验证它们并提供正确的错误消息。



txtAmount.Text.Trim()是一个很好的调用(对于其他文本框也是如此)减少空格。



另外,使用TryParse()来验证NaN和非double值。如果验证失败,则返回false。



Ex: -





is only for "" or String.Empty. What about " " (one space)?

And what about invalid values (NaN - not a number values)? You should modify this code to validate them and give proper error messages.

txtAmount.Text.Trim() is a good call (for the other text box as well) to cut down spaces.

Also, use TryParse() to validate against NaN and non-double values. It returns false if the validation fails.

Ex :-

double amount;

if (double.TryParse(txtAmount.Text, out amount))


确定。请试试这个。



OK. Please try this.

string amountText = txtAmount.Text;
string personsText = txtPerson.Text;

double amount;
double persons;

if (double.TryParse(amountText.Trim(), out amount) && double.TryParse(personsText.Trim(), out persons))
{
    //both amountText and personsText are valid.
    double result = amount / persons;
}
else
{
    //something is invalid. show some error.
}


这篇关于验证文本框我在双数据类型中有价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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