简体   繁体   English

如何在文本框下设置货币格式?

[英]how to currency format under textbox?

I want enter number in textbox, an my textbox convert automatically it in comma(,) format. 我想在文本框中输入数字,我的文本框会自动将其转换为逗号(,)格式。 I have tried to do this, but it works wrong. 我试图这样做,但是它做错了。 Help me? 帮我? Like this 1,20(I JUST ENTER 120); 像这样的1,20(我只要输入120);

private bool IsNumeric(int Val)
{
    return ((Val >= 48 && Val <= 57) || (Val == 8) || (Val == 46));
}
String str;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    int KeyCode = e.KeyValue;
    if (!IsNumeric(KeyCode))
    {
        if (KeyCode == 13)
        {
            e.Handled = true;
            vendas();
            str = null;
        }
        e.Handled = true;
        return;

    }
    else
    {
        e.Handled = true;
    }
    if (((KeyCode == 8) || (KeyCode == 46)) && (str.Length > 0))
    {
        str = str.Substring(0, str.Length - 1);
    }
    else if (!((KeyCode == 8) || (KeyCode == 46)))
    {
        str = str + Convert.ToChar(KeyCode);
    }

    if (str.Length == 0)
    {
        textBox1.Text = "";
    }
    if (str.Length == 1)
    {
        textBox1.Text = "0,0" + str;
    }
    else if (str.Length == 2)
    {
        textBox1.Text = "0," + str;
    }
    else if ((str.Length > 2) && (str.Length != 6) && (str.Length != 9) && (str.Length != 12))
    {
        textBox1.Text = str.Substring(0, str.Length - 2) + "," + str.Substring(str.Length - 2);
        textBox1.Text = textBox1.Text;
    }
    else if ((str.Length > 6) && (str.Length != 8) && (str.Length != 10) && (str.Length != 12))
    {
        textBox1.Text = str.Substring(0, str.Length - 3) + "," + str.Substring(str.Length - 1);
        textBox1.Text = textBox1.Text;
    }
}

It shows me 10,01 instead 0,01? 它向我显示10,01而不是0.01?

What you want is a MaskedTextBox . 您想要的是MaskedTextBox

Simply set of mask of "$999,999,990.00" and any input the user enters must be digits, and there must be at least 3, but the entry can be any number up to the hundreds of millions (if you need billions and trillions, just add more 9s and commas). 只需设置掩码"$999,999,990.00" ,用户输入的任何输入都必须是数字,并且必须至少包含3,但是输入项可以是不超过数亿的任何数字(如果需要数十亿和数万亿,则只需添加更多9s和逗号)。 As the user enters these digits, the formatting will adjust based on the mask. 当用户输入这些数字时,格式将根据掩码进行调整。 Here's the kicker; 这是踢脚; MaskedTextBox respects culture information, so if you specify the French culture, the commas become spaces, the decimal becomes a comma, and the dollar sign becomes the Euro symbol. MaskedTextBox尊重文化信息,因此,如果您指定法国文化,则逗号变为空格,十进制变为逗号,美元符号变为欧元符号。

I was originally going to suggest MaskedTextBox, but MTB is designed for left-to-right style formatting of a fixed (or known in advanced, at least) length string, which makes it not so suitable for currency. 我本来会建议使用MaskedTextBox,但MTB是为固定(或至少在高级方面已知)长度字符串的从左到右样式格式化而设计的,因此它不适用于货币。

First, I'd recommend you avoid doing anything using keycodes or the like, and stick to something a bit more straightforward by just validating and editing the text when it changes: 首先,我建议您避免使用键码或类似方法执行任何操作,而是通过在文本更​​改时进行验证和编辑来坚持一些简单明了的操作:

    void tb_TextChanged(object sender, EventArgs e)
    {
          //Remove previous formatting, or the decimal check will fail
      string value = tb.Text.Replace(",", "").Replace("$", "");
      decimal ul;
          //Check we are indeed handling a number
      if (decimal.TryParse(value, out ul))
      {
            //Unsub the event so we don't enter a loop
        tb.TextChanged -= tb_TextChanged;
            //Format the text as currency
        tb.Text = string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:C2}", ul);
        tb.TextChanged += tb_TextChanged;
      }
    }

例

The main part is string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:C2}", ul); 主要部分是string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:C2}", ul); the en-US ensures it'll always show $ and decmials as '.'s. zh-CN确保将$和decmials始终显示为“。”。 The {0:C2} formats the string as a number ( 0 ) of currency ( :C ) to 2 decimal spaces ( 2 ). {0:C2}将字符串格式设置为货币( :C )的数字( 0 )到2个小数位( 2 )。

This doesn't prevent the user from entering text, but you can keep the previous text (eg '$23.00') and if the user enters something that isn't a number, decimal.TryParse will fail, at which point you can revert the text back to what it was before the user changed it (just by inserting an else block near the end of this event handler). 这不会阻止用户输入文本,但是您可以保留前一个文本(例如'$ 23.00'),如果用户输入的内容不是数字,则使用小数。TryParse将失败,此时您可以还原文本返回到用户更改之前的状态(只需在此事件处理程序的结尾附近插入else块)。

I'd recommend setting the TB text to '$0.00' or something initially, or the cursor will jump when it formats the first change. 我建议将TB文本初始设置为“ $ 0.00”或其他设置,否则在格式化第一个更改时光标会跳。 It also has some selection issues when commas are adding, which you could get around by storing the selection position just before formatting and changing it afterward, or doing something more complex, it's just an example. 在添加逗号时,它还存在一些选择问题,您可以通过在格式化之前存储选择位置并随后进行更改来解决该问题,或者做一些更复杂的事情,这只是一个例子。

Well, at first glance, I notice that nothing about your code whatsoever makes any sense. 好吧,乍一看,我发现关于您的代码的任何事情都没有任何意义。

First and foremost, learn coding standards for indentation . 首先, 学习缩进的编码标准 This code is extremely hard to read. 此代码很难阅读。 I'm tempted to flag this question as offensive for having had to look at it. 我很想将这个问题标记为令人反感,因为必须要考虑它。

Next, this line: 接下来,这一行:

if (!IsNumeric(KeyCode){

Says: if the keycode is NOT numeric do the following stuff, where "the following stuff" is a whole bunch of numeric operations on a keycode which is presumed to be numeric. 说:如果键码不是数字,则执行以下操作,其中“以下键”是对假定为数字的键码进行的一堆数字操作。

Next, str is not defined anywhere in your method. 接下来,在您的方法中的任何地方都没有定义str Maybe it's defined globally, but that would just be silly. 也许它是在全球范围内定义的,但这只是愚蠢的。 Rather, you should just get the current value of it programmatically. 相反,您应该仅以编程方式获取它的当前值。

And finally: you don't need to reinvent the wheel. 最后:您不需要重新发明轮子。 There are tons of tools out there that will do this kind of thing for you. 有大量的工具可以为您做这种事情。 In fact, I'm fairly sure win forms has a native control that'll do this. 实际上,我非常确定win窗体具有将执行此操作的本机控件。 It might even be an attribute of textbox, I don't remember. 我不记得它甚至可能是文本框的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM