Textbox display formatting

前端 未结 5 1341
花落未央
花落未央 2020-12-19 21:30

I want to add \",\" to after every group of 3 digits. Eg : when I type 3000000 the textbox will display 3,000,000 but the value still is 3000000.
I tried to use maskedte

5条回答
  •  攒了一身酷
    2020-12-19 21:42

    This may work fine for your scenario I hope.

     private string text
            {
                get
                {
                    return text;
                }
                set
                {
                    try
                    {
                        string temp = string.Empty;
                        for (int i = 0; i < value.Length; i++)
                        {
                            int p = (int)value[i];
                            if (p >= 48 && p <= 57)
                            {
                                temp += value[i];
                            }
                        }
                        value = temp;
                        myTxt.Text = value;
                    }
                    catch
                    { 
    
                    }
                }
            }
    
        private void digitTextBox1_TextChanged(object sender, EventArgs e)
        {
            if (myTxt.Text == "")
                return;
            int n = myTxt.SelectionStart;
            decimal text = Convert.ToDecimal(myTxt.Text);
            myTxt.Text = String.Format("{0:#,###0}", text);
            myTxt.SelectionStart = n + 1;
        }
    

    Here, myTxt = your Textbox. Set Textchanged event as given below and create a property text as in the post.

    Hope it helps.

提交回复
热议问题