C# 如何选择完整的DataGridView并进行更新?
在C# 如何选择完整的DataGridView并进行更新?,c#,sql,winforms,datagridview,C#,Sql,Winforms,Datagridview,在Form1()中,我从db1获取所有数据。在btnGetDb1\u Click()中是更新db2数据库的代码。从dataGridView1中选择特定行成功。如何在不从dataGridView1中选择任何行并同时更新所有行的情况下实现此功能 public Form1() { InitializeComponent(); DataSet dsForDb1 = new DataSet(); dsForDb1 = client.GetAllFromDb1(); // Got All
Form1()
中,我从db1获取所有数据。在btnGetDb1\u 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();
}
数据绑定完成后,dataGridView1上的DataBound事件将触发。此时,您可以迭代GridView.Rows集合以获取更新第二个数据库所需的数据 如何做到这一点实际上取决于您使用的数据库以及dataGridView1中可能包含的行数-理想情况下,如果有数百行,您不希望为每一行触发单独的查询,因此,如果DBMS允许,请考虑使用表值参数或等效参数
private void dataGridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow row in dataGridView1.Rows)
{
......
}
}