[英]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.