验证文本框位于两个数字

时间:2015-08-14 12:17:49

标签: vb.net winforms

我的WinForms应用程序上有一系列15个TextBox控件。每个名为txtValue1txtValue2,...,txtValue15

enter image description here

我想要做的是确保文本框的值,当更改时,用户失去对该字段的关注(.Leave事件被引发),以比较该值低于其后继者的数值字段但高于其前任字段(如果可用)。

(已经有一个Sub程序,以确保只输入数字,并从正面剪掉额外的零..)

我以前使用过从stackExchange获得的另一个答案中的代码,但是想知道我需要更改什么来使其成为比较呢?

For i As Integer = trkNoOfQuestions.Value To 1 Step -1
        ' The question value
        Dim txts = Me.Controls.Find("txtQuestionValue" & i.ToString, True)
        If txts.Count > 0 Then
            Dim txt As TextBox = txts.First
            txt.Enabled = True
        End If
Next

1 个答案:

答案 0 :(得分:1)

这会有效但有一些限制: - 如果你输入1,2,3,4,5然后决定用1,5改写,你就会被困在这里,因为5大于3.所以你必须重新输入起始最大到最小。 - 您可能需要做一些额外的步法,具体取决于您打算如何处理0。

 Private Sub txtValue1_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles txtValue1.Validating,
        txtValue2.Validating, txtValue3.Validating, txtValue4.Validating, txtValue5.Validating

        Try

            For counter As Integer = 1 To 5 
                Dim txtThis() = Me.Controls.Find(String.Concat("txtValue", counter), True)
                Dim txtPrevious() = Me.Controls.Find(String.Concat("txtValue", counter - 1), True)
                Dim txtNext() = Me.Controls.Find(String.Concat("txtValue", counter + 1), True)
                'compare this textbox to the previous
                If txtThis.Length > 0 AndAlso txtPrevious.Length > 0 Then
                    Dim thisValue As Integer
                    Dim previousValue As Integer
                    Integer.TryParse(txtPrevious(0).Text, previousValue)
                    Integer.TryParse(txtThis(0).Text, thisValue)

                    If thisValue <= previousValue Then
                        If thisValue > 0 AndAlso previousValue > 0 Then

                            e.Cancel = True
                            'show alert
                            Exit For
                        End If
                    End If
                End If

                If txtThis.Length > 0 AndAlso txtNext.Length > 0 Then
                    Dim thisValue As Integer
                    Dim nextValue As Integer
                    Integer.TryParse(txtNext(0).Text, nextValue)
                    Integer.TryParse(txtThis(0).Text, thisValue)

                    If thisValue > nextValue Then
                        If thisValue > 0 AndAlso nextValue > 0 Then
                            e.Cancel = True
                            'show alert
                            Exit For
                        End If
                    End If
                End If


            Next

        Catch ex As Exception
            MessageBox.Show(String.Concat("An error occurred: ", ex.Message))
        End Try

    End Sub