【问题标题】:How to select full DataGridView and update it?如何选择完整的 DataGridView 并更新它?
【发布时间】:2026-01-05 11:40:01
【问题描述】:

Form1(),我从 db1 获取所有数据。 btnGetDb1_Click() 中是更新 db2 数据库的代码。这在从dataGridView1 中选择特定行时成功。如何在不从dataGridView1 中选择任何行并将所有行一起更新的情况下实现这一点?

public Form1()
{
   InitializeComponent();

   DataSet dsForDb1 = new DataSet();
   dsForDb1 = client.GetAllFromDb1(); // Got All The Data From db1
   dataGridView1.DataSource = dsForDb1.Tables[0];
   dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
}

private void btnGetDb1_Click(object sender, EventArgs e)
{
   // Start Updating from db1
   ServiceReference1.UserDetails objuserdetail = 
                                 new ServiceReference1.UserDetails();

   objuserdetail.ID = (int)dataGridView1.CurrentRow.Cells[0].Value;
   objuserdetail.Name = (string)dataGridView1.CurrentRow.Cells[1].Value;
   objuserdetail.Age = (string)dataGridView1.CurrentRow.Cells[2].Value;
   client.UpdateDb2(objuserdetail); // To Update the Data
   MessageBox.Show("Data Updated Successfully");
   client.Close();
}

【问题讨论】:

    标签: c# sql winforms datagridview


    【解决方案1】:

    dataGridView1 上的 DataBound 事件将在数据绑定完成时触发。此时,您可以遍历 GridView.Rows 集合以获取更新第二个数据库所需的数据。

    如何完成实际上取决于您正在使用的数据库以及您在 dataGridView1 中可能拥有的行数 - 理想情况下,您不希望为每一行触发单独的查询(如果有的话)有数百个,因此如果您的 DBMS 允许,请考虑使用表值参数或等效参数。

    private void dataGridView1_DataBound(object sender, EventArgs e)
    {
        foreach (GridViewRow row in dataGridView1.Rows)
        {
             ......
        }
    }
    

    【讨论】:

      最近更新 更多