2015-01-01 36 views
0

當我運行我的代碼標籤保持不變,但是當我調試它,我可以看到文本的變化,然後當它完成捉迷藏爲什麼我的標籤留更改

public void getData(string a) 
{ 
    SqlConnection conn = new SqlConnection(@"Data Source=MASSI\FABERSERVER;Initial Catalog=Data.mdf;Integrated Security=True"); 
    conn.Open(); 
    SqlCommand command = new SqlCommand("Select UserID,UserName,Email FROM Login Where UserName= '" + a + "'", conn); 
    SqlDataReader reader = command.ExecuteReader(); 

    while (reader.Read()) 
    { 
     label1.Text = reader["UserID"].ToString(); 
     label2.Text = reader["UserName"].ToString(); 
     label3.Text = reader["Email"].ToString(); 
    } 

    conn.Close(); 
} 
+1

WebForms?的WinForms? WPF? –

+1

您可能僅在1行之後。在找到單行之後,您的While循環應該退出,並且還應該添加邏輯,以便在使用if(reader.HasRows)時找不到該行。這個鏈接討論了一個更好的方法:http://stackoverflow.com/questions/7836517/enforce-only-single-row-returned-from-datareader但我想它有點高級。 – NoChance

+0

您的應用程序對SQL注入開放。改用參數化查詢。 –

回答

0

就在變回情況下,試試這個:

public void getData(string a) { 
     SqlConnection conn = new SqlConnection(@"Data Source=MASSI\FABERSERVER;Initial Catalog=Data.mdf;Integrated Security=True"); 
     conn.Open(); 
     SqlCommand command = new SqlCommand("Select UserID,UserName,Email FROM Login Where UserName= '" + a + "'", conn); 
     SqlDataReader reader = command.ExecuteReader(); 

     string id, name, email; 

     while (reader.Read()) 
     { 
      id = reader["UserID"].ToString(); 
      name = reader["UserName"].ToString(); 
      email = reader["Email"].ToString(); 

     } 
     conn.Close(); 

     label1.Text = id; 
     label2.Text = name; 
     label3.Text = email; 
    } 
} 

希望它有幫助。

相關問題