Home > Software engineering >  How to prevent to delete specific character with bacspace key
How to prevent to delete specific character with bacspace key

Time:01-29

I want to write temperature in my textbox for example:"38.8". But I dont want to use maskedTextbox.

My code:

  private void textBox_TextChanged() 
  {
     if(textbox. text. length() == 3)
     {
       textbox. Text  = "." ;
     } 
  }

But it doesnt work. I would like that the backspace key avoid comma. How to do that?

CodePudding user response:

Not the best way but will do the job. You can use KeyPress event for your textbox

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
            if ((e.KeyChar != (char)System.Windows.Forms.Keys.Back))
            {

                if ((sender as TextBox).Text.Length == 2)//set dot(.) after 2 numbers.
                {
                    (sender as TextBox).Text  = ".";
                    (sender as TextBox).SelectionStart = this.Text.Length;
                }
            }
        }
  •  Tags:  
  • Related