文本框出错 - 输入字符串格式不正确 [英] Error on a textbox - Input string not in a correct format

查看:92
本文介绍了文本框出错 - 输入字符串格式不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天,

我已经在64位操作系统上开发和应用,WIN 8,它运行完美但在我安装32位的应用程序后,WIN 7机器我遇到错误老实说,我觉得很奇怪。我在Visiual工作室选择了Release和86x。您的紧急回复将不胜感激



我的代码

Good Day,
I have developed and application on a 64 bit OS, WIN 8, it is running perfect but after I installing the app on 32 bit, WIN 7 machine I experience an error which I honestly find it weird. I have selected "Release" and "86x" on my Visiual studio. Your urgent response will be appreciated

my Code

namespace AfricanFoodsPOS
{
    public partial class Payment : Form
    {
        private BindingList<tblproduct> products = new BindingList<tblproduct>();

        AFStagingEntities afNewObject = new AFStagingEntities();

        public delegate void PaymentMadeEvent(object sender, PaymentMadeEventArgs e);

        //public decimal myValue = 0;

        public event PaymentMadeEvent PaymentMade;

        public decimal myPay;
        public decimal MyPay
        {
            get { return myPay; }
            set {
                  myPay = value;
                  txtYouArePaying.Text = String.Format("{0:c}", myPay);                 
                } 
        }

        public decimal paymentAmount;
        public decimal PaymentAmount
        {
            get { return paymentAmount; }
            set
            { 
                paymentAmount = value;             
                txtAmountToPay.Text = String.Format("{0:c}", paymentAmount);                
            }
        }       

        public Payment()
        {
            InitializeComponent();         
              
        }


        //was private
        public void PaymentHasBeenMade(object sender, EventArgs e)
        {
            decimal total = 0;           
            //robust
            try
            {
                decimal YouArePaying = 0;
                decimal AmountToPay = 0;
                YouArePaying = decimal.Parse(txtYouArePaying.Text.TrimStart('R'));
                AmountToPay = decimal.Parse(txtAmountToPay.Text.TrimStart('R'));

                total = YouArePaying - AmountToPay;

                if (total >= 0)
                {
                    MessageBox.Show("Give change: R " + total);
                    PaymentMade(this, new PaymentMadeEventArgs() { PaymentSuccess = true });
                }
                else
                {
                    total = AmountToPay - YouArePaying;
                    txtAmountToPay.Text = total.ToString();

                    MessageBox.Show("Customer is: R " + total + " short.");
                    PaymentMade(this, new PaymentMadeEventArgs() { PaymentSuccess = false });
                }
            }
            catch (Exception exx)
            {
                MessageBox.Show("An error has occured, please enter a valid amount, " + exx.Message);
            }

            finally
            {
                //txtYouArePaying.Dispose();          
            }
        }


        private void Payment_Load(object sender, EventArgs e)
        {

        }     

    }


    public class PaymentMadeEventArgs : EventArgs
    {
        private bool paymentSuccess;

        public bool PaymentSuccess
        {
            get { return paymentSuccess; }
            set { paymentSuccess = value; }
        }
    }

    
}

推荐答案

按照我们的评论,这个解决方案强调了如果要将它们解析为数字,如何清理数据输入。



首先:最好使用数字输入或正则表达式来表示数字控制。这有助于减少服务器端的问题,并可以为用户提供有意义且响应迅速的信息。这并不总是可以做到这一点,所以这就是你如何处理它的服务器端



(哦,NB,我现在是一名网络开发人员,所以当我说服务器端,这也可以指你控件后面的代码作为控制控件行为的代码,我猜我称之为客户端)



所以:解析数值。 int.Parse将从字符串中选择整数,无论​​字母或其他任何内容,甚至小数点。 double.Parse不能忽略其他数字,因为它们可能与数字的结构相关。如果结构不合理,则会抛出错误。



您可以使用double.TryParse检查该值是否可解析。这将返回一个布尔值:True =可以解析而false =无法解析。你也传递一个out参数,所以如果它可以解析,你也会得到结果。



看看:

As per our comments, this solution highlights how to sanitize your data inputs if you want to parse them as numeric.

First: It's always best to use numeric inputs or regex's for numeric controls. This helps reduce the issues on the server side and can provide meaningful and responsive information to the user. It's not always possible to do this, so this is how you can handle it server side

(Oh, NB, I'm currently a web developer, so when I say "server side", this could also refer to the code behind your control as apposed the the code controlling the behavior of the control, which I guess I'd call client side)

So: Parsing numeric values. int.Parse will pick out the integers from a string, regardless of letters or anything else, even decimal points. double.Parse cannot ignore the other digits because they could be relevant to the structure of the number. If the structure is not sound, then it throws an error.

You can check if the value is parse-able by using double.TryParse. This will return a boolean value: True=can parse and false=can't parse. You also pass an out parameter so if it can parse, you also get the result.

Take a look:
string alphanum = "123.abc";
string justnum = "123.456";

double result; //Don't bother setting the out parameter.  It will always change in the tryparse

if(double.TryParse(alphanum,out result){
    Assert.Fail("The parse should return false);
}
Assert.AreEqual(0.0,result);  //whatever the 'result' was set to before, it is now zero
if(double.TryParse(justnum ,out result){
    Assert.AreEqual(123.456,result);
}







使用它你可以在使用它之前检查你的数据。所以如果tryparse失败,告诉用户它的格式是错误的



我希望有帮助^ _ ^

Andy




Using this you can check your data before using it. So if the tryparse fails, tell the user that the format it wrong

I hope that helps ^_^
Andy


这篇关于文本框出错 - 输入字符串格式不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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