使数字文本框像(###,###,###)

时间:2014-05-07 15:31:48

标签: c# winforms string-formatting

我有一个数字文本框,用于分隔这样的数字(###,###,###)并使用此代码:

private void txtnum2_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!char.IsControl(e.KeyChar)
        && !char.IsDigit(e.KeyChar)
        && e.KeyChar != '.')
    {
        e.Handled = true;
        txtnum2.Text += Convert.ToString(e.KeyChar);
    }

    if (e.KeyChar == '.'
        && (sender as TextBox).Text.IndexOf('.') > -1)
    {
        e.Handled = true;
    }

    txtnum2.Text = Regex.Replace(txtnum2.Text, "[^.0-9]", "");


        for (int i = 1, j = 0; i < 10; ++i)
        {
            try
            {
                txtnum2.Text = txtnum2.Text.Insert(txtnum2.Text.Length - ((3 * i) + j), ",");
                ++j;
            }
            catch { }
        }

但是在第一次&#34;之后,&#34;其他数字转到文本框的第一个。

1 个答案:

答案 0 :(得分:0)

在Winforms中(如@drew_w指出的那样),您将使用MaskedTextBox

maskedTextBox1.Mask = "###,###,###";
maskedTextBox1.KeyDown += new KeyEventHandler(txtnum2_KeyPress);

在WPF中,您可以查看this blog posttranslation