C#winforms文本框中的千位分隔符

时间:2013-09-03 13:37:34

标签: c# string string-formatting c#-5.0

我想在我的文本框中放入千位分隔符。我写了下面的代码,但它不能很好地工作。例如:

1-我不能输入30000。

2- 123,456 => 561234。

问题是什么?

private void TextBoxCostTextChanged(object sender, EventArgs e)
{
    try
    {
        var context = this.TextBoxCost.Text;
        bool ischar = true;
        for (int i = 0; i < context.Length; i++)
        {
            if (char.IsNumber(context[i]))
            {
                ischar = false;
                break;
            }
        }
        if (ischar)
        {
            TextBoxCost.Text = null;                         
        }

        **TextBoxCost.Text = string.Format("{0:#,###}", double.Parse(TextBoxCost.Text));**

    }
    catch (Exception ex)
    {
        ExceptionkeeperBll.LogFileWrite(ex);
    }
}

3 个答案:

答案 0 :(得分:2)

我解决了我的问题:

 private void TextBoxCostKeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (!char.IsControl(e.KeyChar)
        && !char.IsDigit(e.KeyChar)
        && e.KeyChar != '.')
                {
                    e.Handled = true;
                }


            }
            catch (Exception ex)
            {
                ExceptionkeeperBll.LogFileWrite(ex);
            }
        }

        private void TextBoxCostTextChanged(object sender, EventArgs e)
        {
            try
            {
                  string value = TextBoxCost.Text.Replace(",", "");
      ulong ul;
      if (ulong.TryParse(value, out ul))
      {
          TextBoxCost.TextChanged -= TextBoxCostTextChanged;
          TextBoxCost.Text = string.Format("{0:#,#}", ul);
          TextBoxCost.SelectionStart = TextBoxCost.Text.Length;
          TextBoxCost.TextChanged += TextBoxCostTextChanged;
      }
            }
            catch (Exception ex)
            {
                ExceptionkeeperBll.LogFileWrite(ex);
            }
        }

答案 1 :(得分:1)

首先,您可以更轻松地检查文本框中的所有字符是numbers,而不是letters

double inputNumber;
bool isNumber = double.TryParse(TextBoxCost.Text, out inputNumber);

其次,您正在使用错误的功能String.Format用于将值插入字符串。 ToString()可用于转换字符串的显示格式(奇怪的术语,但是是的)。

使用以下内容以逗号

获取号码
string withCommas = inputNumber.ToString("#,##0");
TextBoxCost.Text = withCommas;

注意我使用String.Format 。停止使用String.Format

答案 2 :(得分:0)

当在后台更改文本时,

TextBox会将光标位置设置为开头。因此,为了使输入尽可能直观,您需要执行以下操作:

  1. 在当前光标位置拆分字符串并从第一部分删除所有外来字符(包括数千个分隔符,因为您想在之后插入它们)
  2. 获取格式正确的值(如果您的应用需要,可能是输入的数值)
  3. 获取格式化字符串中输入字符串第一部分的最后一个字符的位置(请参阅#1)(通过逐字符比较,跳过千位分隔符)
  4. 更新TextBox
  5. 的值
  6. 将光标位置设置为#3
  7. 计算的位置

    上述算法的唯一问题是,当在正确位置输入千位分隔符时,光标将直接在它之前结束,但解决该问题(并实际编写代码)留作练习;)< / p>