1

我试图通过从多个表中获取数据来填充网格视图。这是我的代码:

 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();


}

这给出了一个错误,提示“关键字'where'附近的语法不正确。” 谁能帮我这个?谢谢

编辑:

忽略字符串缺少连接。这一切都在一条线上,你必须滚动一英里才能看到这一切。他们只是让人们更容易看到。

4

1 回答 1

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();
}
于 2013-06-03T00:30:32.913 回答