如何从货币的用户输入中删除额外的数字以及如何检查用户是否在asp.net c#中没有输入任何内容?

Lil*_*ily 1 c# asp.net currency str-replace

请帮助我,我已经陷入这些问题几天了.我有一个Web表单,将在asp.net中付款,语言是C#.

文本框用于接受来自用户的货币金额.我的要求是,如果用户输入例如75,则在_TextChanged事件中它将切换到75.00.我得到了这部分工作.但我的代码没有检查位置后的三个字符.并删除多余的零.我的问题:1.如果输入超过小数点后的两位数,如何删除多余的零?2.如果用户未在文本框中输入任何数字,我该怎么办?我试过,我只是得到错误或它弄乱了整个代码.

protected void txtAmount_TextChanged(object sender, EventArgs e)
{

        string textBoxData = txtAmount.Text;

        int textLength = textBoxData.Length;

        int position = txtAmountToPay.Text.IndexOf("."); //Position is the decimal

        if (position == -1)
        {
            textBoxData = textBoxData + ".50"; // when you enter 75 you get 75.50
        }
        if (position == textLength -2 )
        {
            textBoxData = textBoxData + "4"; // when you enter 75.0 you get 75.04
        }
        if (position == textLength -1)
        {
            textBoxData = textBoxData + "30"; // when you enter 75. you get 75.30
        }
        if (position >= textLength - 3) // This part does not work
        {
            textBoxData == textBoxData.Replace(-3);// if user enters 75.0000 it will remove all the other digits after the two 0s after the decimal point
        }


    txtAmount.Text = textBoxData.ToString();
 }
Run Code Online (Sandbox Code Playgroud)

Chr*_*ark 5

另一个答案是服务器端验证.如果您使用客户端验证,我认为它会更优化.即使没有回发,它也会验证输入.试着看看这个样本:

<asp:TextBox id="TextBox1" runat="server" />
<asp:RequiredFieldValidator id="RVF1" runat="server" ControlToValidate="TextBox1"
   ErrorMessage="Required" Display="Dynamic" />
<asp:CompareValidator id="CheckFormat1" runat="server" ControlToValidate="TextBox1" Operator="DataTypeCheck"
   Type="Currency"  Display="Dynamic" ErrorMessage="Illegal format for currency" />
<asp:RangeValidator id="RangeCheck1" runat="server" ControlToValidate="TextBox1"
   Type="Currency" Minimum="1" Maximum="999.99" ErrorMessage="Out of range" Display="Dynamic" />
Run Code Online (Sandbox Code Playgroud)

这将验证您的文本输入.

  • 1st:asp:RequiredFieldValidator检查输入是否为空或空;

  • 第二:asp:CompareValidator检查输入是否为货币格式;

  • 和第三:asp:RangeValidator验证你的价值范围.(适用于超值天花板和地板)

这是一个简单的演示.