Visual Basic输入验证

时间:2018-10-01 12:11:52

标签: vb.net

我是Visual Basic编程的新手。我正在使用多行文本框,仅接受来自用户的数字输入。

我需要先删除所有空白,然后再将其添加到列表框中。例如,当(8)添加到列表框中时,它变成8,如果没有输入或只有空白作为输入,我不应该让用户继续进行操作。预先谢谢你:)

For i As Integer = 0 To Val(TxtInput.Lines.Count) - 1
    If TxtInput.Lines(i) = "" Then 'Ignores newline inputs
        'Placeholder Comment 
    ElseIf IsNumeric(TxtInput.Lines(i)) Then 'Tests for Numbers
        Temp.LbInput.Items.Add(TxtInput.Lines(i))
        Temp.Show()
    Else
        MsgBox("Your input must only be in numbers, check for invalid inputs!", 1, "Error")
        Temp.LbInput.Items.Clear()
        Return
    End If
Next

2 个答案:

答案 0 :(得分:0)

这是linq-to-objects的目的:

Dim result = TxtInput.Lines.
        Select(Function(line) line.Trim).
        Where(Function(line) Not String.IsNullOrWhitespace(line) AndAlso IsNumeric(line)).
        Select(Function(line) Val(line))

您也可以这样做:

Dim lines = TxtInput.Lines.Select(Function(line) line.Trim)
If lines.Any(Function(line) Not IsNumeric(line)) Then
    MsgBox("Your input must only be in numbers, check for invalid inputs!", 1, "Error")
    Exit Sub
Else
    Dim result = lines.Where(Function(line) Not String.IsNullOrWhitespace(line)).
                       Select(Function(line) Val(line))

    'Do more with "result" here

End If

答案 1 :(得分:-1)

只需将修剪的线存储到变量中

For i As Integer = 0 To TxtInput.Lines.Count - 1
    Dim line As String = TxtInput.Lines(i).Trim() '<======================

    If line = "" Then 'Ignores newline inputs
        'Placeholder Comment 
    ElseIf IsNumeric(line) Then 'Tests for Numbers
        Temp.LbInput.Items.Add(line)
        Temp.Show()
    Else
        MsgBox("Your input must only be in numbers, check for invalid inputs!", 1, "Error")
        Temp.LbInput.Items.Clear()
        Return
    End If
Next

此外,TxtInput.Lines.Count已经是Integer。无需使用Val进行转换,顺便说一下,它将转换为Double

请注意,您可以将任何类型的项目添加到ListBox中,因此也可以将行转换为所需的类型。我不知道您是否需要IntegerDouble。假设您只需要整数。然后您可以将代码更改为

If TxtInput.Lines.Count = 0 Then
    MsgBox("You have not entered anything. Please enter a number!", 1, "Error")
Else
    For i As Integer = 0 To TxtInput.Lines.Count - 1
        Dim line As String = TxtInput.Lines(i).Trim()
        Dim number As Integer

        If line = "" Then
            MsgBox("Your input is empty. Please enter some numbers!", 1, "Error")
        ElseIf Integer.TryParse(line, number) Then 'Tests for Numbers
            Temp.LbInput.Items.Add(number)
            Temp.Show()
        Else
            MsgBox("Please enter only valid numbers!", 1, "Error")
            Temp.LbInput.Items.Clear()
            Return
        End If
    Next
End If

(代码已根据您的评论更改。)

如果要加倍,只需将number声明为Double并用Double.TryParse(line, number)进行转换。