2015-11-01 138 views
0

我認爲一切都很好,那麼爲什麼數據不會顯示在文本框中。我多次使用此代碼。那麼這裏有什麼錯誤?我在Visual Studio 2012中工作。從數據庫中選擇查詢

string name = comboBox1.SelectedIndex.ToString(); 

query = "select *from Record Where Name='"+name+"'"; 
cmd = new SqlCommand(query, con); 

con.Open(); 
SqlDataReader dr = cmd.ExecuteReader(); 

while (dr.Read()) 
{ 
    textBox1.Text =(dr["Items1"].ToString()); 
    textBox2.Text = (dr["Items1_Charge"].ToString()); 
    textBox3.Text = (dr["Items2"].ToString()); 
    textBox4.Text = (dr["Items2_Charge"].ToString()); 
    textBox5.Text = (dr["Items3"].ToString()); 
    textBox6.Text = (dr["Items3_Charge"].ToString()); 
    textBox7.Text = (dr["Items4"].ToString()); 
    textBox8.Text = (dr["Items4_Charge"].ToString());    
} 
+2

究竟是什麼錯誤?在哪一行?你調試了你的代碼嗎?您的'* from'部分需要一個空格作爲'* from'。 –

+1

哦,不,不要連接字符串查詢。訓練自己使用[參數](http://www.dotnetperls.com/sqlparameter)來防止[SQL注入](https://en.wikipedia.org/wiki/SQL_injection)。 – venerik

+0

也,爲什麼使用while循環來設置相同的控制?假設你期望你的查詢只返回一條記錄,只需調用一次'dr.Read()' –

回答

1

我會懷疑* from應該是* from。另外我會建議使用下面顯示的where條件的參數,特別是當有嵌入撇號的機會時。另外請注意,我添加了HasRows,所以我們確信有東西回來了。我也改變你如何從組合框中獲得當前值

public void Sample() 
{ 
    string name = comboBox1.Text; 
    query = "select * from Record Where Name= @Name"; 

    cmd = new SqlCommand(query, con); 
    cmd.Parameters.AddWithValue("@Name", name); 

    con.Open(); 
    SqlDataReader dr = cmd.ExecuteReader(); 

    if (dr.HasRows) 
    { 
     while (dr.Read()) 
     { 
      textBox1.Text = (dr["Items1"].ToString()); 
      textBox2.Text = (dr["Items1_Charge"].ToString()); 
      textBox3.Text = (dr["Items2"].ToString()); 
      textBox4.Text = (dr["Items2_Charge"].ToString()); 
      textBox5.Text = (dr["Items3"].ToString()); 
      textBox6.Text = (dr["Items3_Charge"].ToString()); 
      textBox7.Text = (dr["Items4"].ToString()); 
      textBox8.Text = (dr["Items4_Charge"].ToString()); 
     } 
    } 
} 
+0

thanx所有我得到它 – Saadii