-1

我想编辑 dataGridView 以及数据库。我有一个按钮,当我在编辑 dataGridview 后单击它时,它将更新数据库。我的第一行完全更新,但其他行没有。这是我的代码

private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    string id = row.Cells["Product ID"].Value.ToString();
                    string name = row.Cells["Product Name"].Value.ToString();
                    string description = row.Cells["Product Description"].Value.ToString();
                    string category = row.Cells["Category"].Value.ToString();
                    string quantity = row.Cells["QTY"].Value.ToString();
                    string buyPrice = row.Cells["Buy Price"].Value.ToString();
                    string sellPrice = row.Cells["Sell Price"].Value.ToString();
                    string date = row.Cells["Date"].Value.ToString();

                    String query = "UPDATE [Stock List Table3] SET  [Product Name] = '" + name + "',[Product Description] = '" + description + "',[Category] = '" + category + "',[QTY] = '" + quantity + "',[Buy Price] = '" + buyPrice + "',[Sell Price] = '" + sellPrice + "',Date = '" + date + "' WHERE [Product ID] = '" + id + "'";
                    m.Update_By_DataGridView_Information(query);
                    m.Load_Table1(dataGridView1);
                    m.Load_Table1(dataGridView4);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }


public void Load_Table1(DataGridView dv)
{
    string query = "SELECT * FROM [Stock List Table3]";
    SqlConnection Conn = create_connection();
    SqlCommand cmd = new SqlCommand(query, Conn);
    try
    {
        SqlDataAdapter sda = new SqlDataAdapter();
        sda.SelectCommand = cmd;
        DataTable dataset = new DataTable();
        sda.Fill(dataset);
        BindingSource bSource = new BindingSource();
        bSource.DataSource = dataset;
        dv.DataSource = bSource;
        sda.Update(dataset);

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

public void Update_By_DataGridView_Information(string query)
{
    try
    {
        SqlConnection Conn = create_connection();
        SqlCommand cmd = new SqlCommand(query, Conn);
        cmd.ExecuteNonQuery();
        Conn.Close();
        //MessageBox.Show("Updated Product Information Successfully", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

这是我在 button2 中的总代码 Error Line catch 块

4

1 回答 1

0

更新第一行后,您datagridview1使用原始数据进行更新

m.Load_Table1(dataGridView1)

然后用相同的值更新下一行......

尝试将Load方法放在foreach循环之外:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    //your update code for row...
}
m.Load_Table1(dataGridView1);
m.Load_Table1(dataGridView4);
于 2013-09-03T12:39:57.450 回答