Search code examples
c#runtimelivestring.format

C# - format specific number using format.string in runtime (live) on texbox


i made code to format number when total lengh is == 11, it run on texbox change, but only format when it have 11 characters, i would like to make it on runtime (live), understood ? Its possible ? See my code:

private void textBox3_TextChanged(object sender, EventArgs e)
        {

            Int64 cpf = Convert.ToInt64(textBox3.Text);
            if (textBox3.TextLength == 11)
            {
                textBox3.Text = string.Format(@"{0:000\.000\.000-00}", Convert.ToInt64(cpf));
            }
        }

Thanks


Solution

  • As lazyberezovsky stated, use a masked textbox, but set the PromptChar to whatever you want. Something along the lines of:

    //In your form_load
    //Based on your code above, assuming textBox3 is a MaskedTextbox    
    textBox3.KeyUp += CheckEvent()
    textBox3.Mask = "000000000000";
    textBox3.PromptChar = 'x'; //set this to a space or whatever you want ' ' for blank!
    
    //check AFTER every key press
    private void CheckEvent(object Sender, KeyEventArgs e)
    {
        if(textBox3.Text.Count() < 12)
        {
            return;
        }
    
        //change the textboxMask when all chars present
        maskedTextBox1.Mask = "0:000.000.000-00";
    }