询问者
想请教如何让textbox只允许(-,.和number)

问题
-
我篇写有关textbox allow 数字(-)和(.)dot 的代码
但是,有关(-)方面无法使用想请帮忙看看 感恩
以下是我的代码
If sg1.Text = "" Then
If Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = "." Or e.KeyChar = "-") And Not Char.IsControl(e.KeyChar) Then
'sg1.Focus()
'sg1.SelectAll()
Else
Try
S1 = CDbl(CStr(sg1.Text))
Catch ex As Exception
'MsgBox("Pls fill correct number")
sg1.Text = ""
End Try
End If
e.Handled = True
End If
全部回复
-
Hi christing,
根据你的描述,我有几个问题想要和你确认一下:
- 似乎你正在做一个类似于计算器的 textbox, 那么 ‘-’ 是否可以出现在任意位置。
- '-' 和 ‘.’ 是否可以重复。
- 你提供的代码位于哪个事件当中?
期待你的更新。
Best Regards,
Xingyu Zhao
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com. -
@感谢你的回复
似乎你正在做一个类似于计算器的 textbox, 那么 ‘-’ 是否可以出现在任意位置。
>>只出现在textbox 第一个位置 比如(-100)
'-' 和 ‘.’ 是否可以重复。
"." 可以重复使用但"-"不可以
If Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = "." Or e.KeyChar = "-") And Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
- 已编辑 christing 2020年7月10日 0:53
-
Hi christing,
你需要再添加一个 TextChanged 事件,参考以下代码:
Private str As String = "" Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress If Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = "."c Or e.KeyChar = "-"c) And Not Char.IsControl(e.KeyChar) Then e.Handled = True End If End Sub Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged TextBox1.SelectionStart = TextBox1.Text.Length If TextBox1.Text.Contains("-") Then If TextBox1.Text.LastIndexOf("-") <> 0 Then TextBox1.Text = str Else str = TextBox1.Text End If Else str = TextBox1.Text End If End Sub
希望可以帮助你解决问题。
Best Regards,
Xingyu Zhao
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.- 已编辑 Xingyu ZhaoMicrosoft contingent staff, Moderator 2020年7月10日 6:28
- 已建议为答案 Xingyu ZhaoMicrosoft contingent staff, Moderator 2020年7月17日 8:54