繁体   English   中英

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 字符串并将其转换为所需的格式。

然后使用CaretIndexCaretIndex放在控件的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;
    }
 }

暂无
暂无

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

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