我如何在数据网格视图中进行编辑以及在C#中更新数据库

本文关键字:编辑 数据库 更新 数据 数据网 网格 视图 | 更新日期: 2023-09-27 18:30:05

我想编辑dataGridView和dataBase。我有一个按钮,当我编辑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);
    }
}

这是我在按钮2中的错误行捕获块的总代码

我如何在数据网格视图中进行编辑以及在C#中更新数据库

更新第一行后,用原始数据更新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);
相关文章: