我试图通过从多个表中获取数据来填充gridview。这是我的代码:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string query = "SELECT RegisterTable.CourseCode,
RegisterTable.courseNumber,
RegisterTable.Term,RegisterTable.Grade,
CourseTable.CourseName,
CourseTable.Level,
CourseTable.Credit
FROM RegisterTable,CourseTable
WHERE StudentID='" + MyGlobals.currentID + "' and
RegisterTable.CourseCode=CourseTable.CourseCode and
RegisterTable.CourseNumber=CourseTable.CourseNumber and
RegisterTable.Term=CourseTable.Term";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
GridView1.DataSource = tab;
GridView1.DataBind();
}
这会出现错误,指出“关键字'附近的语法不正确'。”谁能帮我这个?感谢
答案 0 :(得分:2)
您是否尝试重新编写查询(因此它没有使用交叉连接)?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = null;
SqlCommand cmd = null;
SqlDataAdapter adap = null;
string query = string.Empty();
DataSet ds = null;
DataTable tab = null;
con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
query = "SELECT RegisterTable.CourseCode, RegisterTable.CourseNumber, RegisterTable.Term, RegisterTable.Grade, CourseTable.CourseName, CourseTable.Level, CourseTable.Credit FROM RegisterTable INNER JOIN CourseTable ON RegisterTable.CourseCode = CourseTable.CourseCode AND RegisterTable.CourseNumber = CourseTable.CourseNumber AND RegisterTable.Term = CourseTable.Term WHERE StudentID = @StudentID;";
cmd = new SqlCommand(query, con);
cmd.Parameters.Add("StudentID", SqlDbType.VarChar, 50).Value = MyGlobals.currentID;
ds = new DataSet();
adap = new SqlDataAdapter(cmd);
adap.Fill(ds);
if (ds.Tables.Count > 0) {
tab = ds.Tables(0);
}
GridView1.DataSource = tab;
GridView1.DataBind();
}