如何根据VS2012上另一个数据网格的选定行在数据网格上显示sql队列结果

时间:2014-01-15 22:01:00

标签: c# sql visual-studio-2012 datagrid

这是我的代码:

public void loadGrid1() {
                con.Open();
                cmd = new SqlCommand(@"SELECT StudID, Stud_Lname, Stud_Fname FROM STUDENTS;",con);
                rdr = cmd.ExecuteReader();
                while (rdr.Read()) {
                    dataGridView2.Rows.Add(rdr[0].ToString(), rdr[1].ToString(), rdr[2].ToString());
                }
                con.Close();
}

public void loadGrid3() {
                con.Open();
                cmd = new SqlCommand(@"SELECT Title, Author FROM Books INNER JOIN Borrow ON Borrow.BookID = Books.BookID WHERE Borrow.StudID = '"+dataGridView2.SelectedRows[0].Cells[0].Value.ToString()+"';", con);
                rdr = cmd.ExecuteReader();
                while (rdr.Read()) {
                    dataGridView3.Rows.Add(rdr[0].ToString(), rdr[1].ToString());
                }
                con.Close();
}

loadGrid1是我用来加载grid 1内容的函数,而loadGrid3应该显示grid 3所选学生从grid 1借来的书籍}}。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

首先,您的查询容易受到sql注入。除此之外,您可能想要检查在此处创建的实际查询是什么,如果有的话:

SqlCommand(@"SELECT Title, Author FROM Books INNER JOIN Borrow ON Borrow.BookID = Books.BookID WHERE Borrow.StudID = '"+dataGridView2.SelectedRows[0].Cells[0].Value.ToString()+"';");

也许改成它?:

string qryString = @"SELECT Title, Author FROM Books INNER JOIN Borrow ON Borrow.BookID = Books.BookID WHERE Borrow.StudID = '"+dataGridView2.SelectedRows[0].Cells[0].Value.ToString()+"';"

SqlCommand(qryString);

编辑1:何时调用Loadgrid3方法?

编辑2:尝试并按如下方式更改代码:

public void loadGrid1()
{
    con.Open();
    cmd = new SqlCommand(@"SELECT StudID, Stud_Lname, Stud_Fname FROM STUDENTS;",con);
    rdr = cmd.ExecuteReader();
    while (rdr.Read())
    {
        dataGridView2.Rows.Add(rdr[0].ToString(), rdr[1].ToString(), rdr[2].ToString());
    }

    // check if dataGridView2 has more than 0 rows
    // and then select the first row by default
    if(dataGridView2.Rows.Count > 0)
    {
        dataGridView2.Rows[0].Selected = true
    }
    con.Close();
}

请记住,对于您的直接问题,这是一个肮脏的修复,但您可能希望对datagridview事件等做一些事情。