VB在文本框中检查一个完全正确的数字

时间:2018-10-22 16:16:51

标签: vb.net

看看这张照片。 -http://www.imagebam.com/image/f544011007926944

我要签入Textbox1,在textbox2中输入数字,如果有该数字,我将出现在另一个文本框中。当在textbox1中有类似10,11的数字时,就会出现问题,如果我输入textbox2的数字为1,那么它将被认为是数字1。我只会使用1到80的数字。

我在哪里错了?

  ' Split string based on space
        Dim textsrtring As String = TextBox1.Text
        Dim words As String() = textsrtring.Split(New Char() {" "c})
        Dim found As Boolean = False
        ' Use For Each loop over words
        Dim word As String
        For Each word In words
            If TextBox2.Lines(0).Contains(word) Then
                found = True
                If CheckVar1.Text.Contains(word) Then
                Else
                    CheckVar1.Text = CheckVar1.Text + " " + TextBox1.Text()
                End If
            End If

1 个答案:

答案 0 :(得分:0)

所以我想我知道你想要什么。您的问题是String上的Compare函数正在比较字符串文字,而不是数字'11'包含'1',而Compare的'1'将返回true,因为它包含'1'。您需要将字符串转换为数字,然后将数字相互比较。

Private Sub CompareNumbers()

    'First Textbox that is to be used for compare
    Dim textBox1Numbers As List(Of Integer) = GetNumbersFromTextLine(TextBox1.Text)

    'Second Textbox that is to be used for compare
    Dim textBox2Numbers As List(Of Integer) = GetNumbersFromTextLine(TextBox2.Text)

    'Union List of Common Numbers (this uses a lambda expression, it can be done using two For Each loops instead.)
    Dim commonNumbers As List(Of Integer) = textBox1Numbers.Where(Function(num) textBox2Numbers.Contains(num)).ToList()

    'This is purely for testing to see if it worked you can.
    Dim sb As StringBuilder = New StringBuilder()
    For Each foundNum As Integer In commonNumbers
        sb.Append(foundNum.ToString()).Append(" ")
    Next

    MessageBox.Show(sb.ToString())

End Sub

Private Function GetNumbersFromTextLine(sTextLine As String) As List(Of Integer)

    Dim numberList As List(Of Integer) = New List(Of Integer)()

    Dim sSplitNumbers As String() = sTextLine.Split(" ")

    For Each sNumber As String In sSplitNumbers

        If IsNumeric(sNumber) Then
            Dim iNum As Integer = CInt(sNumber)
            If Not numberList.Contains(iNum) Then
                numberList.Add(iNum)
            End If
        Else
            MessageBox.Show("Non Numeric Found in String :" + sTextLine)
        End If

    Next

    Return numberList

End Function