Search code examples
c#datagridviewmdf

How can I insert a record from a DataGridView component into a mdf database, if I use Windows Forms?


I have a Windows Forms application (not WPF), which has a DataGridView component. The component is linked to a table from a dataset. Everything works fine, the data from the table appears in the DataGridView. However, I don't know how to save a new record, inserted as a new row into the DataGridView into the database.

The user enters the desired values and presses Tab to get to the next column. Once he presses Tab after the last column, the newly created row should be inserted into the table and saved.

I think I have to write something in the RowLeave event handler, but I am not sure. Every similar question I saw here was referring to WPF.

How can I save the new row into the table?

Later edit:

The code that I have:

Load event handler for the window form:

private void frmCursanti_Load(object sender, System.EventArgs e)
{
    // TODO: This line of code loads data into the 'colibriDataSet.Cursanti' table. You can move, or remove it, as needed.
    this.cursantiTableAdapter.Fill(this.colibriDataSet.Cursanti);

}

The saving engine, in the RowLeave event of the dgvCursanti DataGridView, adapted from here:

    private void SaveToCursantiTable(object sender, DataGridViewCellEventArgs e)
    {
        MessageBox.Show("Lorem Ipsum");
        try
        {
            this.Validate();
            this.cursantiBindingSource.EndEdit();
            this.cursantiTableAdapter.Update(this.colibriDataSet.Cursanti);
            MessageBox.Show("Succes!");
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Solution

  • Everything was fine, however I didn't notice a detail: there are TWO .mdf databases generated and maintained by the Database Management System: one in my project directory and the second in the bin directory. I was looking in the one that wasn't updating.