Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do restrict the characters that a TextBox will accept?

You can handle the textbox's KeyPress event and if the char passed in is not acceptable, mark the events argument as showing the character has been handled. Below is a derived TextBox that only accepts digits (and control characters such as backspace). Even though the snippet uses a derived textbox, it is not necessary as you can just add the handler to its parent form.

[C#]

public class NumbersOnlyTextBox : TextBox
{
  public NumbersOnlyTextBox()
  {
    KeyPress += new KeyPressEventHandler( HandleKeyPress );
  }

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

[Visual Basic]

Public Class NumbersOnlyTextBox
  Inherits TextBox
  Public Sub New()
    AddHandler Me.KeyPress, AddressOf HandleKeyPress
  End Sub

  Private Sub HandleKeyPress(ByVal sender As Object, _
      ByVal e As KeyPressEventArgs)
    If Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar)) Then
      e.Handled = True
    End If
  End Sub
End Class

Contributed from George Shepherd's Windows Forms FAQ



Page view counter