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'到数据类型int
有人可以帮助我如何将SqlDataReader转换为String。因为我注意到当我使用varchar / string数据类型检索列时,我没有这种错误但是如果我检索到具有int数据类型的列,则会出现此错误。
答案 0 :(得分:0)
替换它:
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);