错误:
Conversion failed when converting the nvarchar value 'select TopicID from Topic where TopicName='Data Structure'' to data type int
代码:
public void BindGridview()
{
string strConnString = ConfigurationManager.ConnectionStrings["infoConnectionString"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(strConnString);
sqlcon.Open();
string strquery2 = "select TopicID from Topic where TopicName='" + ddltopic.SelectedItem.Text+ "'";
string strquery3 = "select i.name ,i.score from info as i,Topic as t where i.topic_id=@topicid";
SqlCommand cmd = new SqlCommand(strquery3,sqlcon);
cmd.Parameters.AddWithValue("@topicid",strquery2);
cmd.Connection = sqlcon;
SqlDataReader dr;;
this.GridView1.DataSource =cmd.ExecuteReader();
this.GridView1.DataBind();
sqlcon.Close();
}
}
谁能告诉我哪里错了?任何帮助将不胜感激..请尽快回复..提前致谢..
最佳答案
您传递的是整个查询中的而不是此处这一行中的主题 id
cmd.Parameters.AddWithValue("@topicid",strquery2);
然后将其作为参数并将其添加到以下查询中。如果这是一个子查询,你总是可以先执行它,然后在参数中使用结果。
但它失败的原因是因为您实际上是在尝试通过传入查询字符串来比较 String
和 int
。
关于c# - SQL从nVarchar到int的转换报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20278791/