检查文本框是否为空
问题描述:
我目前正在编程一个小登录系统,我试图阻止用户创建没有输入到文本框中的任何帐户。 这是我目前的注册帐户代码:检查文本框是否为空
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
是否有非空值。您正在用这些值替换两个文本框的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
答
你可以试试这个你不评价?正如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 - https://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace(v=vs.110).aspx的 – Ctznkane525
谜 “莫名其妙” 能使用调试器解决。 ** [使用调试器浏览代码](https://msdn.microsoft.com/en-us/library/y740d9d3.aspx)**。这个问题会很快出现。还请阅读[问]并参加[游览] – Plutonix
您的代码没有检查在TextBox中使用什么,它正在检查您以前存储在“My.Settings”中的内容。另外,在你的If语句中,你需要'OrElse'而不是'AndAlso',你可以去掉'ElseIf'并使用'Else'。 – Blackwood