簡體   English   中英

每次按下鍵都會在文本框中自動顯示小數位 VB.NET

[英]EveryTime key is pressed will automatic decimal places in textbox VB.NET

我在我的文本框中使用了按鍵事件。 當我按下“2”時,我的預期值應該是 0.02。 但是它顯示“20.02”

我嘗試將文本框屬性“RighttoLeft”設置為yes,以便在鍵入時從右側開始。 但我希望我鍵入的 keychar 不附加到我在代碼中使用的 FactorDecimal 的 output 中。

請看下面的代碼。 我基於其他帖子的@Visual Vincent 評論:

 Private Sub txtChequeAmt_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtChequeAmt.KeyPress
    If Char.IsDigit(e.KeyChar) = False Then
        e.Handled = True
    End If

    FactorDecimal1.AppendNumber(e.KeyChar)
    txtChequeAmt.Text = FactorDecimal1.ToString()

End Sub

    Public Class FactorDecimal
    Private value As String = "0"

    Public DecimalPlaces As Integer

    Public Sub AppendNumber(Character As Char)
        If Char.IsNumber(Character) = False Then
            Throw New ArgumentException("Input must be a valid numerical Character!", "Character")
            value = (value & Character).TrimStart("0"c)
        Else
            value = (value & Character).TrimStart("0"c)
        End If
    End Sub

    Public Sub RemoveRange(Index As Integer, Length As Integer)
        If value.Length >= Me.DecimalPlaces + 1 AndAlso Index + Length > value.Length - Me.DecimalPlaces Then
            Length -= 1 'Exclude decimal point
        End If

        If Index + Length >= value.Length Then
            Length = value.Length - Index 'Out of range
            value = value.Remove(Index, Length)
        End If

        If value.Length = 0 Then
            value = "0"
        End If
    End Sub

    Public Overrides Function ToString() As String
        Dim Result As Decimal

        If (Decimal.TryParse(value, Result)) = True Then
            Return (Result / (10 ^ Me.DecimalPlaces)).ToString("0." & New String("0"c, Me.DecimalPlaces))

        End If

        Return (Result / (10 ^ Me.DecimalPlaces)).ToString("0." & New String("0"c, Me.DecimalPlaces))
    End Function

    Public Sub New(DecimalPlaces As Integer)
        If DecimalPlaces <= 0 Then
            DecimalPlaces = 1
        End If
        Me.DecimalPlaces = DecimalPlaces
    End Sub
End Class

如果您想在文本框中使用您的計算,您需要設置 e.Handled = True。

Private Sub txtChequeAmt_KeyPress(sender As Object, e As KeyPressEventArgs) 
    If Char.IsDigit(e.KeyChar) = False Then
        e.Handled = True
        ' No point to continue if it is not a digit because 
        ' in that case you throw into the AppendNumber. Better avoid the exception
        Return
    End If

    FactorDecimal1.AppendNumber(e.KeyChar)
    txtChequeAmt.Text = FactorDecimal1.ToString()

    ' Don't let the forms engine add the number to your textbox 
    ' you have already defined its content 
    e.Handled = True
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM