简体   繁体   中英

thousand separator in C# winforms texbox

i want to put thousand separator in my textbox. i have written following code but it does not work well. for example :

1- i cannot type 30000.

2- 123,456 => 561,234.

what is the problem?

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);
    }
}

i solved my problem:

 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);
            }
        }

First, you can have an easier way to check that all characters in your text box are numbers , not letters .

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

Second, you are using the wrong function . String.Format is used for inserting values into a string. ToString() can be used to transform the display format of a string (odd terminology, but yeah).

Use the following to get the number with commas

string withCommas = inputNumber.ToString("#,##0");
TextBoxCost.Text = withCommas;

Notice I am NOT using String.Format . Stop using String.Format

TextBox es tend to set the cursor position to the beginning when the text is changed in the background. So, for the input to be as intuitive as possible, you need to do the following:

  1. Split the string at the current cursor position and remove all foreign characters (including thousands separators, because you want to insert them afterwards) from the first part
  2. Get the correctly formatted value (and maybe the numerical value of the input, if your application cares for that)
  3. Get the position of the last character of the first part of the input string (see #1) in the formatted string (by comparing them character-wise, skipping the thousands separators)
  4. Update the value of your TextBox
  5. Set the cursor position to the position calculated at #3

The only problem with the above algorithm will be that when entering a thousands separator at the right position, the cursor will end up directly before it, but solving that (and actually writing the code) is left as an exercise ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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