Hi friends,
I wanted to restrict my text box to have only 10 characters.I have used the following code

Private Sub txtSpouseWorkPhone_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSpouseWorkPhone.KeyDown
        If txtSpouseWorkPhone.TextLength > 10 Then
            MsgBox("Only 10 characters are alowed", MsgBoxStyle.Critical, "Invalid PAN No")
            txtSpouseWorkPhone.Text = txtSpouseWorkPhone.Text.Substring(0, (txtSpouseWorkPhone.TextLength - 1))
        End If

But I have a small problem ie.
once the focus leaves the text box,I am not able to make further chances in it.ie.the message box appears irrespective of the keys we press, after 10 characters.

Why don't you raise the event on TextChanged instead?

Private Sub txtSpouseWorkPhone_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSpouseWorkPhone.TextChanged

Edited 5 Years Ago by Techyon: fixed code

Why cant u set the MAXLength propery of textbox to 10?

Edited 5 Years Ago by Pgmer: n/a

This question has already been answered. Start a new discussion instead.