错误消息“输入字符串格式不正确” [英] Error message "Input string was not in correct format"

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

问题描述

请在下面的代码中更正以上错误:



我做错了什么



Please correct the above error in the codes below :

What am I doing wrong

//
               //outstanding Balance  starts
               //

               //txt_Balance.Text = "0";

               decimal mExpect = Convert.ToDecimal(txt_Expect_Amt.Text);
               txt_Expect_Amt.Text = mExpect.ToString("N");


               decimal mAct = Convert.ToDecimal(txt_Actual_Disb.Text);
               txt_Actual_Disb.Text = mAct.ToString("N");


               


               if (txt_Prev_Actual_Disb.Text.Length == 0)
                   txt_Prev_Actual_Disb.Text = " ";




               decimal mPrev = Convert.ToDecimal(txt_Prev_Actual_Disb.Text);



              txt_Prev_Actual_Disb.Text = mPrev.ToString("N");



              

               decimal mCurr = Convert.ToDecimal(txt_Tranche.Text);

               decimal mTot = mCurr + mPrev;
               decimal mOut = mExpect - mTot;


               txt_Balance.Text = mOut.ToString("N");


               ////

推荐答案

Convert.ToDecimal(string) [ ^ ]如果输入字符串不是a,则使用抛出此类异常的方法十进制值的有效表示。您必须处理此类异常,可能会通知用户他/她必须提供有效的输入值。
The Convert.ToDecimal(string)[^] method you are using throws such an exception if the input string is not a valid representation of a Decimal value. You have to handle such exceptions, possibly notifying the user he/she must provide valid input values.


您需要检查每个TextBox的内容以获取有效输入。



Decimal.TryParse方法为您提供了一种有效的方法;这是一个例子:
You need to check the content of each TextBox for valid input.

The Decimal.TryParse method gives you an efficient way to do that; here's an example:
decimal decimalValue;

if (! Decimal.TryParse(textBox1.Text, out decimalValue))
{
    // invalid decimal input
    //
    // throw an error ?
    //
    // warn the user with a dialog ?
    //
    // halt execution ?
    return;
    //
    // assign some default value to 'decimalValue ?
}

// if you reach this point in the code
// 'decimalValue contains a valid decimal

根据您的应用程序,当输入TextBoxes中的文本不是有效的十进制格式时,您可能会实现不同的响应:上面代码中的注释建议使用这些替代方案。



更好的策略,imho,当你有多种情况只使用TextBoxes进行某些类型的数字输入时,就是创建您自己的子类TextBox,并修改其KeyHandler事件,以便用户只能以正确的格式输入文本。总是更好地尽快捕获输入错误。

Depending on your application, you might implement different responses when the text in the input TextBoxes is not in valid Decimal format: some of those alternatives are suggested by comments in the code above.

A better strategy, imho, when you have multiple cases of using TextBoxes for certain types of numeric entry only is create your own sub-classed TextBox, and modify its KeyHandler events so that the user can only enter text in the correct format. Always better to catch input errors as soon as possible.


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

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