我有多個數據在database
所以我需要加他們在不同的textBoxes
。 這裏是我的代碼如何搜索數據庫中的數據並將其添加到C#中的文本框?
private void Search_button1_Click(object sender, EventArgs e)
{
string query = string.Empty;
if (ID_textBox1.Text.Trim().Length > 0)
{
try
{
query = "SELECT ProductName,ProductDescription,SellPrice FROM Table2 WHERE ProductID='" + ID_textBox1.Text + "'";
SqlConnection Conn = CreateConnection.create_connection();
SqlCommand cd = new SqlCommand(query, Conn);
SqlDataReader reader = cd.ExecuteReader();
while (reader.Read())
{
Name_textBox2.Text = reader["ProductName"].ToString();
Description_textBox3.Text = reader["ProductDescription"].ToString();
Unit_Price_textBox5.Text = reader["SellPrice"].ToString();
}
reader.Close();
Name_textBox2.Text = Name_textBox2.Text;
Description_textBox3.Text = Description_textBox3.Text;
QTY_textBox4.Text = 1.ToString();
Unit_Price_textBox5.Text = Unit_Price_textBox5.Text;
Price_textBox6.Text = (decimal.Parse(QTY_textBox4.Text) * decimal.Parse(Unit_Price_textBox5.Text)).ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
那麼問題是什麼? –
爲什麼你將'TextBox'中的值分配給自己?另外,學會使用參數化查詢來避免SQL注入,並且您希望查詢中只有一行結果?如果你有多行,只有最後一行的數據會在不同的文本框中出現。 – Tim
什麼是'1.ToString()'應該產生? '1'不是有效的變量名稱。如果你想爲該文本框賦值1,只需使用'QTY_textBox4.Text =「1」;'。 – Tim