C# TextBox 转换数字

C# TextBox convert numbers

我有一个文本框,我只能通过 KeyPress 接受数字,但我不能用逗号分隔输入数字。

private void inputAmount_KeyPress(object sender, KeyPressEventArgs e)
{
  if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
  {
    e.Handled = true;
    // this doesn't work
    inputAmount.Text = string.Format("{0:#,##}", e.KeyChar);
  }
}

我正在寻找的是: 当用户开始在文本框中输入数字时,它在用户输入时用逗号分隔千位。

有什么想法吗?

更新

我添加了第二个函数 TextChanged,如下所示,并从上面的代码中删除了 inputAmount.Text = string.Format("{0:#,##}", e.KeyChar); 行。

它确实在我的输入中添加了千位分隔符,但它一直跳到数字的开头

private void inputAmount_TextChanged(object sender, EventArgs e)
{
  inputAmount.Text = string.Format("{0:#,##0}", double.Parse(inputAmount.Text));
}

已解决

这是我解决问题的最终代码

    // Only accept numbers
    private void inputAmount_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
        {
            e.Handled = true;
        }
    }

    // Add thousand separators while user typing
    private void inputAmount_TextChanged(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(inputAmount.Text))
        {
            System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
            int valueBefore = Int32.Parse(inputAmount.Text, System.Globalization.NumberStyles.AllowThousands);
            inputAmount.Text = String.Format(culture, "{0:N0}", valueBefore);
            inputAmount.Select(inputAmount.Text.Length, 0);
        }
    }

检查 int.TryParse 输入的文本是否为数字。 然后加上当前字符的inputAmount字符串,转换成需要的格式。

然后将 CaretIndex 放在 inputAmount.SelectionStart 控件的末尾。

下面的代码展示了如何做到这一点

private void inputAmount_KeyPress(object sender, KeyPressEventArgs e)
{
    int number = 0;
    bool success = int.TryParse(e.KeyChar.ToString(), out number);
    if (success)
    {
        string input = (inputAmount.Text + e.KeyChar).Replace(",", "");
        inputAmount.Text = String.Format("{0:n0}", Convert.ToInt32(input));
        inputAmount.SelectionStart = inputAmount.Text.Length;
        e.Handled = true;
    }
 }