I need data from database on my textbox when i choose the particular data in drop-down list. I do the following code but it give me the number instead of description.
int s1 = DropDownList3.SelectedIndex;
SqlCommand query = new SqlCommand("Select description from vul_auto where finding_id= " + s1,con);
TextBox3.Text =(query.ExecuteNonQuery()).ToString();
ExecuteNonQuery
returns the number of rows affected. You would use this to do an insert/update/delete, not to select data. Instead, you should use ExecuteScalar
.
Also, as a general best practice, always use parameterised queries instead of concatenating, specially when you are accepting input from user.
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
}
}
As @user3713775 mentions in his answer, use Convert.ToString
to handle null values.
@shree.pat18 is correct. Use query.ExecuteScalar() & use ConvertToString() instead of ToString() for more robustness. like TextBox3.Text = Convert.ToString(query.ExecuteScalar());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.