vb.net - 每次按下键都会在文本框 VB.NET 中自动显示小数位
问题描述
我在我的文本框中使用了按键事件。当我按下“2”时,我的预期值应该是 0.02。但是它显示“20.02”
我尝试将文本框属性“RighttoLeft”设置为yes,以便在键入时从右侧开始。但我希望我键入的 keychar 不附加到我在代码中使用的 FactorDecimal 的输出中。
请看下面的代码。我基于其他帖子的@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
推荐阅读
- c# - 通过反射 C# 调用静态类列表
- react-native - 我可以在不安装“react-native 链接”的情况下使用原生基础吗?
- php - 如何合并具有根属性的xml文件?
- wordpress - Wordpress 自定义端点返回 404
- python - discord.py-rewrite 无法添加反应,“Bot”对象没有属性“add_reaction”
- c# - 使用 ASP.NET Core MVC 获取用户输入
- r - 是否有用于格式化国际货币字符串的 R 库或函数?
- python - Pandas 中用户定义的扩展窗口
- html - 将 HTML 文本放在 CSS rgba 层的前面
- asp.net-core - 如何在 Asp.net 核心剃须刀页面的布局页面中检索临时数据