Here's what I had to do to supress invalid characters in a paste event. It's
probably not the best way but it works. There could be some efficiency
issues if the value of the textbox gets large but it shouldn't be a problem
very often for what I'm doing.
dim mblnIgnoreChanges as Boolean = False
dim mblnKeyStroke as Boolean = False
TextBox_KeyPress(...)
if char.isletterordigit(e.KeyChar) = false andalso
convert.toint32(e.KeyChar) <> 8 Then
e.Handled = True
else
mblnKeyStroke = True
end If
end sub
TextBox_TextChanged(...)
if not mblnKeyStroke andalso not mblnIgnoreChanges Then
' text changed by some event other than a keystroke.
dim strNewText As String = String.Empty
for each ch as Char in TextBox.Text
if char.IsLetterOrDigit(ch) = False Then
' do nothing
else
strNewText &= ch
end if
next
mblnIgnoreChanges = True
TextBox.Text = strNewText
mblnIgnoreChanges = False
End If
mblnKeyStroke = False
end Sub
Thanks everyone for your responses.
Itar
"Itar" wrote:
I'm having a problem supressing characters in a text box. I only want alpha
numeric characters (no special chars). I can handle the TextBox_KeyPress
event to supress the invalid characters when the user types them in, however
that doesn't handle the user pasting invalid characters. I thought to use
the MouseDown event but I couldn't figure out how to tell if the user is
trying to paste or is copying the text. To paste the text the user would
have to right-click to pull down the context menu and select paste.
My question: How can I tell if the user is trying to paste text to the
textbox?
Is there an event raised on paste?
or do I have to tell the user selected paste from the context menu?
(ok, that's 3 questions) :)
Thanks in advance