使用数据库中的选定项填充文本框
本文关键字:填充 文本 数据库 | 更新日期: 2023-09-27 17:57:03
private void fillProduct() {
SqlConnection conn = new SqlConnection("Data Source=STATION21''SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
conn.Open();
string query = "Select prodID from product";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0) {
cmbPCode.DataSource = dt;
cmbPCode.DisplayMember = "prodID";
cmbPCode.ValueMember = "prodID";
}
private void cmbPCode_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=STATION21''SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
con.Open();
string query = "Select * from product where prodID = '"+cmbPCode.Text+"'".ToString();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read()) {
tbdc.Text = dr["prodDescription"].ToString();
}
}
我无法根据所选索引从数据库中获取我的项目 我收到此错误
转换varchar 值时转换失败 'System.Data.DataRowView' to data type int
有人可以帮我如何将 SqlDataReader 转换为字符串。 因为我注意到当我检索具有 varchar/string 数据类型的列时,我没有遇到这种错误,但是如果我检索具有 int 数据类型的列,我会收到此错误。
替换它:
string query = "Select * from product where prodID = '"+cmbPCode.Text+
"'".ToString();
有了这个:
string query = "Select * from product where prodID = "+cmbPCode.Text;
建议:您的查询对SQL注入开放,我建议您使用参数化查询来避免它们。
使用参数化查询:
string query = "Select * from product where prodID = @ID";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@ID",cmbPCode.Text);