Search code examples
c#key-events

Why KeyPressEventArgs's e.Handled does nothing in KeyPressEventArgs C#?


This code ( Found through internet ) seems like does nothing at all. How can I prevent non-numeric characters in my TextBox

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

What's the actual purpose of e.Handled? Explanation needed.


Solution

  • if you want to prevent non-numeric characters in TextBox then only 1 line is sufficient to handle the event

    e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);