Вопрос

Here in Form1(), I am getting all data from db1. In btnGetDb1_Click() is the code to update db2 database. This is successful on selecting specific row from dataGridView1. How to implement this without selecting any row from dataGridView1 and updating all the rows together?

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();
}
Это было полезно?

Решение

The DataBound event on dataGridView1 will fire when the data bind is complete. At this point, you can iterate over the GridView.Rows collection to get the data you need for the update of the second database.

How that is done is dependent really on the database you are using and the number of rows you're likely to have in dataGridView1 - ideally, you don't want to be firing a separate query for every row if there are going to be hundreds of them, so look at using a table valued parameter or equivalent if your DBMS permits.

private void dataGridView1_DataBound(object sender, EventArgs e)
{
    foreach (GridViewRow row in dataGridView1.Rows)
    {
         ......
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top