Also, das Thema ist eigentlich extrem Umfangreich. Hier ist ein sehr einfaches Beispiel wie man von TextBox ein neues Control ableitet, dass die Eingabe nach bestimmten Regeln prüft (und ein eigenes Property implementiert).
Imports System.ComponentModel
Public Class NumOnlyTextBox
Inherits TextBox
Private _decimalPositions As Integer
Protected Overrides Sub OnKeyPress(ByVal e As KeyPressEventArgs)
Dim KeyAscii As Integer
Dim shDecimalPositions As Short
Dim shLenDecimals As Short
Dim X As Short
Dim decSep As String = _
System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.Cur_
rencyDecimalSeparator
KeyAscii = Asc(e.KeyChar)
Select Case KeyAscii
Case 8, 13 'backspace, & carriage return
'Do nothing to these
Case 48 To 57 'digits 0-9
X = InStr(Me.Text, decSep)
If X > 0 Then
X = Me.Text.Length - X + 1
If X > DecimalPositions Then
KeyAscii = 0
End If
Else
Me.Text = FormatNumber(CDec(Me.Text & Chr(KeyAscii)), 0)
Me.SelectionStart = Len(Me.Text)
KeyAscii = 0
End If
Case 45 'minus sign
'The number can only have one minus sign, so
'if we already have one, throw this one away
If InStr(Me.Text, "-") <> 0 Then
KeyAscii = 0
End If
'if the insertion point is not sitting at zero
'(which is the beginning of the field), throw away the(minus)
'sign (because it's not valid except in first position)
If Me.SelectionStart <> 0 Then
KeyAscii = 0
End If
Case 46 'This is the period (decimal point)
'if we already have a period, throw it away, if this key
'will exceed decimal positions, then throw away.
If DecimalPositions > 0 Then
If InStr(Me.Text, decSep) <> 0 Then
KeyAscii = 0
End If
Else
KeyAscii = 0
End If
Case Else
'provide no handling for the other keys
KeyAscii = 0
End Select
'If we want to throw the keystroke away, then set the event
'as already handled. Otherwise, let the keystroke be handled normally.
If KeyAscii = 0 Then
e.Handled = True
Else
e.Handled = False
End If
End Sub
<DefaultValue("0"), _
Description("Number of decimal positions"), _
Category("Behavior")> _
Public Property DecimalPositions() As Short
Get
Return _decimalPositions
End Get
Set(ByVal Value As Short)
_decimalPositions = Value
End Set
End Property
End Class |