SQL语句只返回一条记录

时间:2013-03-10 15:09:17

标签: c# ms-access-2007

在订单表中,我有以下数据:

OrderNum | Item | Quantity|
1234     | EE1  | 1       |
1234     | EE3  | 1       |
1235     | EE2  | 1       |
1236     | EE5  | 1       |
1236     | EE8  | 1       |

我想在datagridview中显示订单号为1234的订单。

这是我的代码..但它只显示一条记录......仅限EE1项目。

        con.Open();
        com.CommandText = "SELECT * FROM Orders WHERE OrderNo="+Convert.ToInt32(txtStudNo.Text)+"";

        reader = com.ExecuteReader();


        int indx = dataGridView1.Rows.Add();
        DataGridViewRow row = dataGridView1.Rows[indx];

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                com2.CommandText = "SELECT Description, Price FROM Books WHERE BookID='" + reader[2].ToString() + "'";
                reader2 = com2.ExecuteReader();
                    if (reader2.Read())
                    {
                        row.Cells[0].Value = reader[2].ToString();
                        row.Cells[1].Value = reader2[0].ToString();
                        row.Cells[2].Value = reader[4].ToString();
                        row.Cells[3].Value = reader2[1].ToString();
                    }

                }

需要一些帮助..请。

1 个答案:

答案 0 :(得分:1)

您正在将所有记录写入一行:

dataGridView1.Rows[indx];

要不覆盖已经写入gridview的数据,必须增加indx值并为每条记录获取另一行参考。

也许以下代码适合您?

con.Open();
com.CommandText = "SELECT * FROM Orders WHERE OrderNo="+Convert.ToInt32(txtStudNo.Text)+"";

reader = com.ExecuteReader();

if (reader.HasRows)
{
    while (reader.Read())
    {
        int indx = dataGridView1.Rows.Add();
        DataGridViewRow row = dataGridView1.Rows[indx];

        com2.CommandText = "SELECT Description, Price FROM Books WHERE BookID='" + reader[2].ToString() + "'";
        reader2 = com2.ExecuteReader();

        if (reader2.Read())
        {
            row.Cells[0].Value = reader[2].ToString();
            row.Cells[1].Value = reader2[0].ToString();
            row.Cells[2].Value = reader[4].ToString();
            row.Cells[3].Value = reader2[1].ToString();
        }
    }
}