VB.NET TextBox 只允许输入1-100之间的整数 简洁篇

本文介绍了一段VB.NET代码,该代码用于实现一个文本框中只能输入整数,并且数值范围限定在1到100之间。通过正则表达式过滤非数字字符,并使用异常处理确保输入的有效性和安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1     Dim Str As String = ""
 2     Private Sub txtRecond_KeyUp(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles txtRecond.KeyUp
 3         txtRecond.Text = Regex.Replace(txtRecond.Text, "[^0-9]", "")
 4         If txtRecond.Text = "" Then
 5             Return
 6         End If
 7         Try
 8             Dim num As Integer = Integer.Parse(txtRecond.Text)
 9             txtRecond.Text = num.ToString()
10             If (num > 100) Or (num = 0) Then
11                 txtRecond.Text = ""
12             End If
13         Catch ex As Exception
14             txtRecond.Text = ""
15         End Try
16 
17 
18     End Sub
19 
20     Private Sub txtRecond_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtRecond.KeyPress
21         If Char.IsDigit(e.KeyChar) Or e.KeyChar = Chr(8) Or e.KeyChar = "." Then
22             If e.KeyChar = "." And InStr(txtRecond.Text, ".") > 0 Then
23                 e.Handled = True
24             Else
25                 e.Handled = False
26             End If
27         Else
28             e.Handled = True
29         End If
30 
31     End Sub
View Code

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值