Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Modify KeyPress Event For Multiple Objects

I have a program that has to preform some validation when ever the KeyPress event is fired from a textbox.

Now instead of modifying the KeyPress event for every one of my textboxes, is there a way in .net to modify it in one place and then have that code execute whenever any one of my textfields has a key press event?
[328 byte] By [Jaden] at [2007-11-11 10:22:06]
# 1 Re: Modify KeyPress Event For Multiple Objects
There are two ways to do that. One is to create a KeyPress event procedure and list all the associated textboxes in the procedure's Handles clause:

Private Sub TextBox_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox1.KeyPress, TextBox2.KeyPress, TextBox3.KeyPress ' ...etc.

End Sub

The other is to create your own control which Inherits from TextBox and which overrides the OnKeyPress event:

Public Class MyTextBox
Inherits System.Windows.Forms.TextBox

Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
MyBase.OnKeyPress(e)
' Your validation code here
End Sub

End Class

Then instead of placing standard a TextBox on your form, use your new MyTextBox class.

You should be aware that KeyPress validation does not prevent the user from pasting invalid text from the clipboard. You're better off using the TextChanging or Validating events.
Phil Weber at 2007-11-11 20:48:03 >
# 2 Re: Modify KeyPress Event For Multiple Objects
I attempted your suggestion of creating the custom control. However, as soon as I tell it to inherit from System.Windows.Forms.TextBox, I get an error saying that the Base class cannot be different...etc etc. (I would have written down the error had it been more pertenant.) Oddly enough, when I goto it's suggested fixes, there's one item that leaves the code exactly the way it ism but for some reason gets rid of the error. I am curious now what it's changing to fix this error, because it doesn't change anything in my code that I can see.

Anyways, thank you for the the suggestion, it worked perfectly. And I hadn't considered the copy/paste issue.
Jaden at 2007-11-11 20:49:04 >