The method below should return ds which will be bounded to a datagridview but I am getting error message that says
Must declare the scalar variable "@ID"
public DataSet GetPatientSessions() {
string connStr = ConfigurationManager.ConnectionStrings["connstr"].ToString();
string cmdStr = @"SELECT ROW_NUMBER()OVER(ORDER BY ID) AS SEQ,
ID,
DAT,
S_HOUR,
E_HOUR,
KIND,
ENOPER,
ENDATETIME
FROM SEANCE
WHERE SICK_ID=@SICK_ID
ORDER BY ENDATETIME ASC;";
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(cmdStr, conn)) {
try {
conn.Open();
cmd.CommandText = cmdStr;
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
cmd.Parameters.Add(new SqlParameter("@SICK_ID", SqlDbType.Int)).Value = Convert.ToInt32(TB_PatientID.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
//da.SelectCommand = cmd;
da.Fill(ds, "PatientSessions");
return ds;
}
catch (Exception ex) {
string ErrorMsg = ex.Message.Substring(0, Math.Min(ex.Message.Length, 1024));
return null;
}
}
}
How can I resolve this error?
2条答案
按热度按时间js5cn81o1#
You add the parameter to your SqlCommand but then you don't associate this SqlCommand to the SqlDataAdapter. Thus, when you execute the SqlDataAdapter.Fill method your adapter has no knowledge of that parameter
You just need to use the DataAdapter's SelectCommand property or pass your command to the SqlDataAdapter constructor
pu3pd22g2#
Either pass
cmd
toSqlDataAdapter
's constructor as Steve suggestedOr assign
cmd
to theSelectCommand
of theSqlDataAdapter
: