如何选择完整的DataGridView并更新它?

时间:2014-05-02 21:34:32

标签: c# sql winforms datagridview

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();
}

1 个答案:

答案 0 :(得分:0)

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

如何完成取决于您正在使用的数据库以及您在dataGridView1中可能拥有的行数 - 理想情况下,您不希望为每一行触发单独的查询如果它们将有数百个,那么如果您的DBMS允许,请查看使用表值参数或等效参数。

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