如何在mySQL中检索数据并将其放在datagridview中的特定单元格中

时间:2013-05-23 08:55:44

标签: c# datagridview mysqldatareader

我想将数据库中的quantity列放在datagridview中,首先将数据加载到其中,5列与列quantity一起。现在我尝试在我的数据库中加载列quantity。这是我的代码:

using (MySqlConnection con = new MySqlConnection(serverstring))
{
    string query = @"SELECT quantity 
                    FROM tblOrder_Products
                    WHERE order_ID=@ID";

    con.Open();
    using (MySqlCommand cmd = new MySqlCommand(query, con))
    {
        DataTable dt = new DataTable();

        cmd.Parameters.AddWithValue("@ID", txtboxID.Text);
        MySqlDataReader dr = cmd.ExecuteReader();
        dt.Load(dr);

        dr.Close();


        dataGridView2.DataSource = dt;
        // I want to change this line or this part of code because 
        // I want to put only the column `quantity` which means
        //retaining the data loaded previously in the datagridview
}

所以我的问题是如何在不删除或覆盖之前加载的数据视图的情况下将其放入datagridview中?

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您已经在网格中填充了数据,并且您想要更改属于列Quantity的单元格的内容并引用使用ID单元格的行在数据库中查找更新的值。

在这种情况下,您不应该使用数据表再次重新绑定网格,而只需执行命令,检索更新的值并为请求ID的行设置单元格Quantity

using (MySqlCommand cmd = new MySqlCommand(query, con))
{
    cmd.Parameters.AddWithValue("@ID", txtboxID.Text);
    object result = cmd.ExecuteScalar();
    if(result != null)
    {
        int quantity = Convert.ToInt32(result);
        // Now you need to find the row that contains the ID passed 
        DataGridViewRow row = grid.Rows
                             .Cast<DataGridViewRow>()
                             .Where(r => r.Cells["ID"].Value.ToString().Equals(txtBoxID.Text))
                             .First();
        row.Cells["Quantity"].Value = quantity;
    }
}

<强>更新
在您的评论之后,现在很明显您查询返回了许多记录,并且您希望更新DataGridView中的许多行。
这可以通过以下更改来实现:

// The query returns also the Variant column from the database
// The column is needed to identify the corresponding row to update on the datagridview
// Also I am supposing that the variant column is from the same table (JOIN required otherwise)
string query = @"SELECT variant, quantity 
                FROM tblOrder_Products
                WHERE order_ID=@ID";

con.Open();
using (MySqlCommand cmd = new MySqlCommand(query, con))
{
    cmd.Parameters.AddWithValue("@ID", txtboxID.Text);

    // Cannot use a ExecuteScalar, we need a SqlDataReader to loop over the results
    SqlDataReader reader = cmd.ExecuteReader();
    while(reader.Read())
    {
        int quantity = reader.GetInt32(1);

        // Now I am supposing the the Variant column is of string type, change the Get 
        // accordingly if it is not 
        string v = reader.GetString(0);

        // Use the value retrieved from the database to identify the row to update
        DataGridViewRow row = grid.Rows
                             .Cast<DataGridViewRow>()
                             .Where(r => r.Cells["variant"].Value.ToString().Equals(v))
                             .First();
        row.Cells["Quantity"].Value = quantity;
    }
}