i want to make a textbox that only can support the hex number.
how to make the validation???
thx a lot
Printable View
i want to make a textbox that only can support the hex number.
how to make the validation???
thx a lot
Here is one way of doing it:The above will not allow the user to type in anything but hexadecimal characters, however it's not bullet proof since you could still paste something that contains something else so you should always validate the string. Passing it to the following function could do that:Code:Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Not "1234567890ABCDEF".Contains(Char.ToUpper(e.KeyChar)) AndAlso e.KeyChar <> vbBack Then
e.Handled = True
End If
End Sub
Code:Public Function IsHex(ByVal str As String) As Boolean
Try
Dim num As Long = CLng("&H" & str)
Return True
Catch ex As Exception
Return False
End Try
End Function
There is the following method which you might want to research in a bit more depth which might be of help to you:
Code:Integer.Parse(stringToEvaluate, Globalization.NumberStyles.HexNumber)
VB Code:
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress e.Handled = Not System.Uri.IsHexDigit(e.KeyChar) End Sub
thx
it works
yw
thread resolve
Aren't you better off handling the text-changed event to cover copy-pasting?
Hmm, good point. Well then, there's only one sane, logical thing to do...
...And thats to erase the functionality of TextBoxBase's paste!
Muahahaha! :evil:VB Code:
Dim PasteMethod As Reflection.MethodInfo = _ Array.Find(Of Reflection.MethodInfo)(DirectCast(TextBox1, TextBoxBase).GetType.GetMethods, _ New Predicate(Of Reflection.MethodInfo)(Function(meth As Reflection.MethodInfo) meth.Name = "Paste")) Dim newPaste() As Byte = {0, 0, 0, 0, 0, 0, 0, 42} Dim hndlePaste As System.Runtime.InteropServices.GCHandle = _ System.Runtime.InteropServices.GCHandle.Alloc(CType(newPaste, Object), System.Runtime.InteropServices.GCHandleType.Pinned) Dim addPaste As IntPtr = hndlePaste.AddrOfPinnedObject() System.Reflection.Emit.MethodRental.SwapMethodBody(GetType(TextBoxBase), PasteMethod.MetadataToken, addPaste, newPaste.Length, _ System.Reflection.Emit.MethodRental.JitImmediate)
Unfortunately, Microsoft frowns on this and won't let me modify anything that has already been loaded by the JIT.
So since we can't do that - yeah, Text_Change event is probably best. :(
</joke>