0

これは私のコードです:

Private Sub prices_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles wholeprice_input_new_item.KeyPress, dozenprice_input_new_item.KeyPress, detailprice_input_new_item.KeyPress, costprice_input_new_item.KeyPress

        Dim TxtB As TextBox = CType(sender, TextBox)
        Dim rex As Regex = New Regex("^[0-9]*[.]{0,1}[0-9]{0,1}$")

        'MsgBox(TxtB.Text())    

        If (Char.IsDigit(e.KeyChar) Or e.KeyChar.ToString() = "." Or e.KeyChar = CChar(ChrW(Keys.Back))) Then
            If (TxtB.Text.Trim() <> "") Then
                If (rex.IsMatch(TxtB.Text) = False And e.KeyChar <> CChar(ChrW(Keys.Back))) Then
                    e.Handled = True
                End If
            End If
        Else
            e.Handled = True
        End If

    End Sub

テキストボックスの Text プロパティには、最後に押された文字が含まれていません。例:

 Text entered = "12.1"
 TxtB.Text = "12."

 Text entered = "11.."
 TxtB.Text = "11."

 Text entered = "12"
 TxtB.Text = "1"

すべての文字を検証したい。キープレスイベントでテキストボックス内のすべての文字を検証するにはどうすればよいですか?

4

2 に答える 2

1

問題は、KeyPress イベントで、押されたキーがまだテキスト ボックスに追加されていないことです。次のように、押されている文字を既存のテキストに追加できます。

Dim TxtB As TextBox = CType(sender, TextBox)
If (Char.IsDigit(e.KeyChar) OrElse e.KeyChar = "."c Then
    Dim fullText As String = TxtB.Text & e.KeyChar
    'Do validation with fullText
End If
于 2012-05-11T21:40:45.660 に答える
1

実際には、それよりも少し複雑です。たとえば、ユーザーがバックスペース キーを押した場合はどうなるでしょうか。代わりに TextChanged イベントを使用することをお勧めします。このイベントは、最後に押されたキーによって Text プロパティが更新された後に発生します。

于 2012-06-22T14:56:14.180 に答える