2017-12-27 408 views
-2

我目前正在編程一個小登錄系統,我試圖阻止用戶創建沒有輸入到文本框中的任何帳戶。 這是我目前的註冊帳戶代碼:檢查文本框是否爲空

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 

不知何故,它總是會說:「錯誤的用戶名或密碼」即使我輸入的東西我如何讓它只響應「錯誤的用戶名或密碼」。如果輸入什麼都沒有?

編輯: 我修正了代碼。但是,我如何才能讓這個人只能用他登記的信息登錄?

+0

而是做String.IsNullOrWhiteSpace - https://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace(v=vs.110).aspx的 – Ctznkane525

+1

謎 「莫名其妙」 能使用調試器解決。 ** [使用調試器瀏覽代碼](https://msdn.microsoft.com/en-us/library/y740d9d3.aspx)**。這個問題會很快出現。還請閱讀[問]並參加[遊覽] – Plutonix

+3

您的代碼沒有檢查在TextBox中使用什麼,它正在檢查您以前存儲在「My.Settings」中的內容。另外,在你的If語句中,你需要'OrElse'而不是'AndAlso',你可以去掉'ElseIf'並使用'Else'。 – Blackwood

回答

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

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