0

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

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

                }

需要一些帮助..拜托。

4

1 回答 1

1

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

dataGridView1.Rows[indx];

为了不覆盖已写入网格视图的数据,您必须增加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();
        }
    }
}
于 2013-03-10T15:24:58.147 回答