Vb.net 检查文本框是否为空
我目前正在编写一个小的登录系统,我试图阻止用户创建一个没有在文本框中键入任何内容的帐户。 这是我注册帐户的当前代码:Vb.net 检查文本框是否为空,vb.net,debugging,Vb.net,Debugging,我目前正在编写一个小的登录系统,我试图阻止用户创建一个没有在文本框中键入任何内容的帐户。 这是我注册帐户的当前代码: 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
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
不知何故,即使我输入了一些东西,它也总是会说错误的用户名或密码。如果输入为空,如何使其只响应错误的用户名或密码
编辑:
我修正了密码。但是我如何才能使该用户只能使用其注册的信息登录?请检查My.Settings.username和My.Settings.password是否具有非空值。您正在用这些值替换两个文本框的文本属性。你可以这样做:
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时,您没有进行计算。您能试试这个吗?正如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
改为使用String.IsNullOrWhiteSpace-可以使用调试器以某种方式解决此问题。这个问题很快就会出现。另外,阅读并获取您的代码并不是检查文本框中输入的用法,而是检查您以前存储在My.Settings中的内容。另外,在If语句中需要OrElse而不是AndAlso,您可以去掉ElseIf,只使用Else。@Blackwood如何检查用户输入?检查前不要覆盖它。TrimTextBox1.Text.Length<1是检查TextBox1是否为空的一种方法,但如果要检查TextBox1或TextBox2是否为空,请使用OrElse而不是AndAlso。