Have you ever needed a Windows.Forms.TextBox control that only accepted letters, or that only accepted numbers? Well, the other day, I needed one and after some playing around, I decided that it's something I may well need in the future. Taking the simple logic contained below, you can easily subclass the Winows.Forms.TextBox control and stick it in your toolbox for later use. <Note that for the sake of illustration, I created two extra Booleans to use in the evaluation...you could save yourself two lines of code by including them directly>
Private Overloads Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress Dim isKey As Boolean = e.KeyChar.IsDigit(e.KeyChar) Dim isDecimal As Boolean = e.KeyChar.ToString = "." If Not isKey And Not isDecimal Then e.Handled = True End If End Sub |
| Private Overloads Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress Dim isKey As Boolean = e.KeyChar.IsDigit(e.KeyChar) If isKey Then e.Handled = True End If End Sub |
| Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged If Not IsNumeric(TextBox2.Text) Then Exit Sub If CType(TextBox2.Text, Int16) < 20 Then TextBox2.BackColor = Color.Red Else TextBox2.BackColor = Color.WhiteSmoke End If End Sub |
| Private Sub tbFirstName_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles tbFirstName.GotFocus, tbLastName.GotFocus, tbPhysician.GotFocus, tbSSN.GotFocus CType(sender, TextBox).BackColor = Color.LightGray End Sub Private Sub tbFirstName_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles tbFirstName.LostFocus, tbLastName.LostFocus, tbPhysician.LostFocus, tbSSN.LostFocus CType(sender, TextBox).BackColor = Color.White End Sub |