C# 如何根据dropdownlist中的选定值在文本框中显示数据
当我在下拉列表中选择特定数据时,我需要文本框中数据库中的数据。 我执行以下代码,但它给我的是数字而不是描述C# 如何根据dropdownlist中的选定值在文本框中显示数据,c#,sql,asp.net,C#,Sql,Asp.net,当我在下拉列表中选择特定数据时,我需要文本框中数据库中的数据。 我执行以下代码,但它给我的是数字而不是描述 int s1 = DropDownList3.SelectedIndex; SqlCommand query = new SqlCommand("Select description from vul_auto where finding_id= " + s1,con); TextBox3.Text =(query.ExecuteNonQuery()).ToString(); Exe
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
处理空值。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()) @shree.pat18是正确的。
使用query.ExecuteScalar()&使用ConvertToString()而不是ToString(),以增强健壮性。
比如TextBox3.Text=Convert.ToString(query.ExecuteScalar()) 使用
Convert.ToString()
很好。我已经把它包括在我的答案中。这是一个使用Convert.ToString()
的好方法。我已把它包括在我的答复中。