vb.net - VB.net 需要文本框只接受最大和最小数字
问题描述
Imports System.Drawing
Imports System.Text.RegularExpressions
Imports System.Windows.Forms
Module Module1
Public Enum ValidationType
MaxMin = 1
End Enum
Public Sub AssignValidation(ByRef CTRL As TextBox, ByVal Validation_Type As ValidationType, Min As Double, Max As Double)
Dim txt As TextBox = CTRL
Select Case Validation_Type
Case ValidationType.MaxMin
AddHandler txt.TextChanged, AddressOf MaximumMinimum
End Select
End Sub
Public Sub MaximumMinimum(ByVal sender As Object, ByVal e As System.EventArgs)
Dim NO As TextBox = sender
If Val(NO.Text) < Min Then
NO.Focus()
ElseIf Val(NO.Text) > Max Then
NO.Focus()
End If
End Sub
End Module
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AssignValidation(Me.TextBox1, ValidationType.MaxMin,Zo.Min,Zo.Max)
End Sub
我对该代码有疑问。如果我有多个文本框,并且所有文本框都有不同的最大值和最小值,那么这些最小值和最大值在模块中为每个文本框声明,那么如何将这些值添加到该代码中?
因为该代码暂时显示 Min=0 和 Max=0 但实际上我有不同的值。
解决方案
您可以使用对象字典到元组来存储最小值/最大值。(如果您想要自定义错误消息或颜色等,您可以向元组添加更多内容)
Option Strict On
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AssignValidation(Me.TextBox1, ValidationType.MaxMin, 5, 10)
AssignValidation(Me.TextBox2, ValidationType.MaxMin, 0, 5)
End Sub
End Class
Module Module1
Private ranges As New Dictionary(Of Object, Tuple(Of Double, Double))()
Public Enum ValidationType
MaxMin = 1
End Enum
Public Sub AssignValidation(CTRL As TextBox, Validation_Type As ValidationType, Min As Double, Max As Double)
Select Case Validation_Type
Case ValidationType.MaxMin
If Not ranges.ContainsKey(CTRL) Then ranges.Add(CTRL, New Tuple(Of Double, Double)(Min, Max))
AddHandler CTRL.TextChanged, AddressOf MaximumMinimum
End Select
End Sub
Public Sub MaximumMinimum(sender As Object, e As System.EventArgs)
Dim textbox = DirectCast(sender, TextBox)
Dim value As Double
If Double.TryParse(textbox.Text, value) Then
' SUCCESS - parsed as Double
If value >= ranges(sender).Item1 AndAlso value <= ranges(sender).Item2 Then
' SUCCESS - within min and max
Else
' FAIL - outside min or max
textbox.Focus() ' what does this even do?
End If
Else
' FAIL - did not parse as Double
MessageBox.Show(textbox.Text)
End If
End Sub
End Module
* 编辑为使用 .NET 7.0 之前的元组语法
推荐阅读
- javascript - 如何用他的名字调用一个函数作为一个字符串?
- sql - 在 PostgreSQL 中计算时间间隔
- python - 单元测试文件夹的好地方:在源代码文件夹中,在它之外,还是......?
- sql - SQL 新手 - 如何比较两组连接表中的数据
- html - 如何在 HTML 中创建 3 列
- javascript - 使用 husky 对 json 文件预提交进行排序
- python - django.apps:当我在 get_models() 上循环时,模板渲染期间出现错误
- scala - spark中的静态分配如何工作?
- r - 当块包含 ggplot 图像时,render / build_site 不起作用
- java - 中断其他进程的线程