-1

How to update database from datagridview without button? I want to write in cells and after leaving row should be automatically updated? any idea? thanks

I tried this. I don't know what event

personneservice ps = new personneservice();

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    personne p = new personne(id, nom, prenom, sexe, profession, salaire);
    ps.update(p);
    MessageBox.Show("Bien modifié ");
    actualiser();
}



void actualiser ()
{
    dataGridView1.Rows.Clear();
    foreach (personne p in ps.findAll())
    {
        String[] row = new String[] { p.Id + "", p.Nom, p.Prenom, p.Sexe, p.Profession, p.Salaire + "" };
        dataGridView1.Rows.Add(row);
    }
}
Maciej Jureczko
  • 1,560
  • 6
  • 19
  • 23
aresdev
  • 31
  • 8

1 Answers1

0

This is not my own work, i found this online.

Here: https://social.msdn.microsoft.com/Forums/en-US/231be175-12d3-44ef-9222-875643a9e7fb/saving-the-data-entered-in-the-datagridview-to-database-table?forum=winformsdatacontrols

  1. Add DataGridView Control in the form
  2. Select that control and and open DataGridView Tasks clicking on ">" simbol
  3. Open Choose DataSource Combo and click on "Add Project DataSource..."
  4. Select Database > Next > Select/Create Connection > Next > Select Table you want to fill in the control > Finish
  5. This will create a DataSet object will be shown in your form along with auto generated Adapter object too.
  6. Select and right click on DataSet object control in designer and Select Edit in DataSet Designer... > this will open related XSD file
  7. Right click on the opened UI for the dataset and Select Configure...
  8. Select Advance Options button... This window will have all the insert, update, delete and other query's checkboxes selected, keep it as it is and press OK
  9. Then press Next and select "Create methods to send updates directly to the database option" [default, it is selected] > Next and Finish it. This will generate required code for doing operations automatically
  10. Add the following code in your Form class,

This will fill up the datagridview

    private void DataGridViewDirectDBUpdate_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'northwindDataSet.Users' table. You can move, or remove it, as needed.
        this.yourtableadaptor.Fill(this.yourdataset.yourtable);

    }

This will save the data back to the database

    private void dataGridView1_CellEndEdit(object sender, EventArgs e)
    {
        this.yourtableadaptor.Update(yourdataset);
    }
James Morrish
  • 455
  • 6
  • 24