首页 > 解决方案 > 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 但实际上我有不同的值。

标签: vb.net

解决方案


您可以使用对象字典到元组来存储最小值/最大值。(如果您想要自定义错误消息或颜色等,您可以向元组添加更多内容)

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 之前的元组语法


推荐阅读