[英]How to display data on textbox based on selected value from dropdownlist
當我在下拉列表中選擇特定數據時,我需要文本框中的數據庫數據。 我執行以下代碼,但是它給了我編號而不是描述。
int s1 = DropDownList3.SelectedIndex;
SqlCommand query = new SqlCommand("Select description from vul_auto where finding_id= " + s1,con);
TextBox3.Text =(query.ExecuteNonQuery()).ToString();
ExecuteNonQuery
返回受影響的行數。 您將使用它來執行插入/更新/刪除操作,而不是選擇數據。 相反,您應該使用ExecuteScalar
。
另外,作為一般的最佳實踐,請始終使用參數化查詢而不是連接查詢,尤其是在您接受用戶輸入時。
using (SqlConnection conn = new SqlConnection(yourconnectionstring))
{
string sql = "Select description from vul_auto where finding_id=@id";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@id", SqlDbType.Int);
cmd.Parameters["@id"].Value = s1;
try
{
conn.Open();
TextBox3.Text = Convert.ToString(cmd.ExecuteScalar());
}
catch (Exception ex)
{
//Handle exception
}
}
正如@ user3713775在他的答案中提到的那樣,使用Convert.ToString
處理空值。
@ shree.pat18是正確的。 使用query.ExecuteScalar()並使用ConvertToString()而不是ToString()來提高魯棒性。 像TextBox3.Text = Convert.ToString(query.ExecuteScalar());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.