0

我想将quantity我的数据库中的列放在 datagridview 中,其中首先加载了数据,5 列与 column 一起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 而不删除或覆盖之前加载的数据?

4

1 回答 1

2

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

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

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;
    }
}
于 2013-05-23T09:18:07.783 回答