2011-09-28 40 views
2

在這裏有幾個問題。正如你所知道的,我創建了一個類,其中生病只是在我的.aspx頁面實例化它。在我的.aspx頁面上,我得到了一個名爲login1的logincontrol。現在我得到錯誤user.UserName = Nothing時,並在此user.UserName = Nothing停止說Object reference not set to an instance of an object..Could你能幫我調試問題。我想要的是,如果用戶名不在數據庫上,lblmessage應該說錯誤用戶名無效如果它是正確的,那麼它將檢查密碼。請幫忙。感謝和更多的權力傢伙。登錄控制如果用戶名未找到標籤文本應回答用戶名未找到

ASPX頁面

Protected Sub LoginButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) 
    Dim user As New User 
    Dim userDAL As New UserDAL 
    user = userDAL.SelectByUsername(Login1.UserName) 
    If user.UserName = Nothing Then 
     Login1.FailureText = "Invalid Username" 
    Else 
     If Login1.Password <> user.Password Then 
      Login1.FailureText = "Invalid password" 
     Else 
      Login1.FailureText = "success" 
     End If 
    End If 

End Sub 

UserDAL.vb

Public Function SelectByUsername(ByVal userName As String) As User 
    Try 
     'select * from User where Username = 'userName' 
     Dim sqlConn As New SqlConnection(_connString) 
     sqlConn.Open() 

     Dim sqlCmd As New SqlCommand("select * from [Users] where Username = '" & userName & "'", sqlConn) 

     Dim dr As SqlDataReader = sqlCmd.ExecuteReader() 

     'Create user collection 
     Dim user As User = Nothing 

     While dr.Read() 
      'Create User object 
      user = New User 
      user.UserName = dr("UserName").ToString 
      user.Password = dr("Password").ToString 
      user.FirstName = dr("FirstName").ToString 
      user.Surname = dr("Surname").ToString 

     End While 
     dr.Close() 

     Return user 
    Finally 
     If _sqlConn IsNot Nothing Then 
      If _sqlConn.State = Data.ConnectionState.Open Then 
       _sqlConn.Close() 
      End If 
     End If 
    End Try 
    Return Nothing 
End Function 

回答

1

而是與user.Username比較,首先你只user即比較,

If user Is Nothing Then 

爲什麼Bcoz在SelectByUsername功能你正在返回Nothing,如果它是無效的用戶名。試試並回復。

+0

先生它仍然是不設置到對象的實例相同的對象引用。現在指向如果user.UserName = String.Empty然後 – Janwel

+0

@Janwel看到編輯答案和答覆。 –

+0

現在先生有一個錯誤,說operator'='沒有爲類型'用戶'和'用戶'定義 – Janwel

0

我會就此與最簡單的答案。添加一個驗證摘要你控制它返回代碼所需的值(「用戶名無效」),然後驗證做

if(Page.IsValid) (This is C# code but VB should be very close to this) 

這應該解決您的問題。

這裏有一個快速片段

 <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> 
     <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="User Name Not Valid" ControlToValidate="TextBox1"></asp:RequiredFieldValidator> 

現在請注意此錯誤信息將顯示在文本框的右側,但是你可以風格它,甚至將其設置爲驗證組。

驗證摘要所需的字段驗證程序或驗證組強制客戶端驗證與ASP.NET的回發所以當提交按鈕觸發它將運行測試並確定是否Page.IsValid == true或false;

http://msdn.microsoft.com/en-us/library/aa479013.aspx

+0

我該怎麼做先生? – Janwel

+0

@Janwel請參閱修改 – CBRRacer

相關問題