Number value in textbox to add commas

Viewed 45

I have tried adding a button to add commas inside as shown below:

protected void Button1_Click(object sender, System.EventArgs e) {
    Number.Text = "";
    string s = string.Format("{0:n0}",1234567890);
    Number.Text += "value : 1234567890";
    Number.Text += "<br />Thousands Separator: " + s;

    Number.Text += "<br/><br />another solution";
    int value = 1234567890;
    string formatedstring = value .ToString("#,##0");
    Number.Text += "<br />result: " + formatedstring;
}

However, I want this to change as soon as I type it in, similar to an update function in Unity. Adding a button function is very unethical.

1 Answers

Make an event for text changed in the textbox. Then add the following code:

 void numberTextBox_TextChanged(object sender, EventArgs e)
    {
      string value = numberTextBox.Text.Replace(",", "");
      ulong ul;
      if (ulong.TryParse(value, out ul))
      {
        numberTextBox.TextChanged -= numberTextBox_TextChanged;
        numberTextBox.Text = string.Format("{0:#,#}", ul);
        numberTextBox.SelectionStart = numberTextBox.Text.Length;
        numberTextBox.TextChanged += numberTextBox_TextChanged;
      }
    }
Related