2012-02-03 128 views
0

我在這裏,因爲我有一個問題。我有剛剛創建的代碼。當用戶輸入正確的用戶名和密碼時,我的代碼正常工作。所以我的問題是當用戶插入錯誤的用戶名和密碼錯誤消息不會顯示。這裏是我的代碼:C#登錄消息警告

MyDs.Clear(); 
MyDa.SelectCommand = Conn.CreateCommand(); 
MyDa.SelectCommand.CommandText = 
    "select * from PersonalName where [email protected] and [email protected]"; 
MyDa.SelectCommand.CommandType = CommandType.Text; 
MyDa.SelectCommand.Parameters.Add("@first", DbType.String, 25, "Firstname").Value = textbox_Username.Text; 
MyDa.SelectCommand.Parameters.Add("@last", DbType.String, 25, "Lastname").Value = textbox_Password.Text; 

MyDa.Fill(MyDs); 
foreach (DataRow item in MyDs.Tables[0].Rows) 
{ 
    if (textbox_Username.Text != item[1].ToString() || textbox_Password.Text != item[3].ToString()) 
    { 
     MessageBox.Show("not connected"); 
    } 
    else 
    { 
     MessageBox.Show("Connected"); 
    } 
} 

任何人都可以告訴我這段代碼有什麼問題?

回答

0

如果輸入錯誤的用戶名,您的數據集將會是空的。這將更接近你想要的:

if (MyDs.Tables[0].Rows.Count > 0) 
{ 
    // you don't need to check username, the SQL query took care of that 

    if (textbox_Password.Text == item[3].ToString()) 
     MessageBox.Show("Connected."); 
    else 
     MessageBox.Show("Failed."); // wrong password 
} 
else 
    MessageBox.Show("Failed."); // no such user 
+0

感謝您的幫助。問題解決了。 :) – Sephiroth111 2012-02-04 04:48:50

+0

現在「接受」這個答案,我們都會很高興:) – egrunin 2012-02-04 07:47:15

0

如果查詢返回任何記錄becasue firast和姓氏不存在,的foreach不執行什麼也沒有發生......

你需要測試myDa是空的,以及,你的代碼僅適用於檢查有效的用戶。

+0

謝謝你的邏輯。我嘗試了斷點,當我執行程序時,錯誤的信息沒有檢查它是否錯誤,但是檢查它是否正確。 – Sephiroth111 2012-02-04 04:56:59