检查TextBox是否为空

时间:2017-12-27 18:26:25

标签: vb.net debugging

我目前正在编写一个小型登录系统,我试图阻止用户创建一个没有在TextBox中输入任何内容的帐户。 这是我目前注册帐户的代码:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    TextBox1.Text = My.Settings.username
    TextBox2.Text = My.Settings.password

    If Trim(TextBox1.Text).Length < 1 AndAlso Trim(TextBox2.Text).Length < 1 Then
        MsgBox("Wrong username or password!")
    ElseIf Trim(TextBox1.Text).Length > 1 AndAlso Trim(TextBox2.Text).Length > 1 Then
        MsgBox("Your account was created!", MsgBoxStyle.Information, "Create")
        Me.Hide()
        Form1.Show()
    End If
End Sub

不知何故,它总是会说“用户名或密码错误”,即使我输入了一些内容。如果输入什么都没有,我该怎么做才回复“用户名或密码错误?”

编辑: 我修复了代码。但是,如何才能使该人只能使用他注册的信息登录?

2 个答案:

答案 0 :(得分:0)

请检查My.Settings.usernameMy.Settings.password是否为非空值。您正在用这些值替换两个文本框'Text属性。你可以这样做:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    If Not String.IsNullOrWhitespace(My.Settings.username) Then
        TextBox1.Text = My.Settings.username
    End If
    If Not String.IsNullOrWhitespace(My.Settings.password) Then
        TextBox2.Text = My.Settings.password
    End If      


    If String.IsNullOrWhitespace(TextBox1.Text) or String.IsNullOrWhitespace(TextBox2.Text) Then
        MsgBox("Wrong username or password!")
...

请注意,在您的代码中,您未评估何时TextBox1.Text.Trim().Length = 1和/或TextBox2.Text.Trim().Length = 1

答案 1 :(得分:0)

你能试试吗?正如Emilio上面提到的那样,请确保您的My.Settings.username和My.Settings.password没有传递任何值。

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
   TextBox1.Text = My.Settings.username
   TextBox2.Text = My.Settings.password

   If String.IsNullOrEmpty(TextBox1.Text) AndAlso String.IsNullOrEmpty(TextBox2.Text) Then
      MsgBox("Wrong username or password!")
   Else
      MsgBox("Your account was created!", MsgBoxStyle.Information, "Create")
      Me.Hide()
      Form1.Show()
   End If
End Sub