2016-05-24 42 views
1

我试图建立在C#中的TextBox/Windows窗体项目,这样,当使用键盘或数字键盘在价格的用户类型,文本框会格式化输入序列看起来像一个价格。转换序列为价格

示例:用户类型1-5-0(减去破折号),文本框的文本值将为1.50美元。

这里是我想要的代码:

private string KeySequence; 

// ... 

private void TxtValue_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if(char.IsDigit(e.KeyChar)) 
    { 
     KeySequence += e.KeyChar.ToString(); 

     if (KeySequence.Length > 0) 
     { 
      txtValue.Text = "$" + (decimal.Parse(KeySequence)/100).ToString("0.00"); 
     } 
    } 
} 

的问题是,每当我在一个值类型,第一个字符始终是我打的最后一个关键,其次是“$”和价钱。所以如果我输入150,格式化文本显示为:0$1.50

我就在想,这是由于KeyDown事件KeyPress之前被调用,所以我试图与处理代码为压制它:

private void TxtValue_KeyDown(object sender, KeyEventArgs e) 
{ 
    txtValue.Clear(); 
} 

但是,这仍然没有工作。

我能做些什么来阻止第一个字符出现?

+1

要取消按键,设定'e.Handled'到TRUE; –

+0

工作就像一个魅力。谢谢! –

回答

1

KeyPress事件之后,击键将仍然由控制处理。

为了防止这种情况,在事件处理程序中设置e.Handled = true;

0

我建议创建一个从NumericUpDown继承的自定义控制。然后,您将拥有一个专门用于处理数字的控件,可自动处理小数位和千位分隔符,提供向上和向下控件以方便递增,并可附加/预先添加适当的货币符号。

我偷的this answer的格式化部分。利用这一点,你的新类看起来是这样的:

public class NumericUpDownCurrency : NumericUpDown 
{ 
    public NumericUpDownCurrency() 
    { 
     DecimalPlaces = 2; 
     Increment = 1; 
     ThousandsSeparator = true; 
    } 

    protected override void UpdateEditText() 
    { 
     ChangingText = true; 
     var decimalRegex = new Regex(@"(\d+([.,]\d{1,2})?)"); 
     var m = decimalRegex.Match(Text); 
     if (m.Success) 
      Text = m.Value; 
     ChangingText = false; 
     base.UpdateEditText(); 
     ChangingText = true; 
     Text = Value.ToString("C", CultureInfo.CurrentCulture); 
    } 
} 

该类添加到您的项目和建设。然后您应该在工具箱中看到NumericUpDownCurrency,并允许将它放在表单上。其余的控件完成。