Windows C # file access database data not persisting on close

I am creating a Windows application using C #, which allows me to access an empty Access database that contains two tables: Provinces and Locations. I am working on a form that just deals with a province table that looks like this:

enter image description here

This is a sub-format. When it is open I can insert / update records, etc. Whenever I make changes, I click the Load Table button to display the changes in the DataGridView.

If I close this subform and display it again, I can click the Load Table button and call all the data to display in the DataGridView. However, if I close the application completely, I lose all my data. I prove this by double clicking the database file to run it in Access where I see the data is definitely gone. This has become a mystery as I cannot figure out why the data is not being saved in the file. Please advise.

Below is the code of the form. You can see from my methods that I try to close the connection object every time I execute the function. So I don't understand why I keep losing data on the application?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GTI_Taxi_Pricing
{
public partial class frmProv : Form
{
    private OleDbConnection connection = new OleDbConnection();
    public frmProv()
    {
        InitializeComponent();
        connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=TaxiDB.accdb;Persist Security Info=False;";                
    }

    private void btnLoad_Click(object sender, EventArgs e)
    {
        try
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            String query = "SELECT * FROM Provinces;";
            command.CommandText = query;
            OleDbDataAdapter da = new OleDbDataAdapter(command);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            connection.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show("Error: " + ex);
        }
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        if (txtName.Text == "")
        {
            MessageBox.Show("The name field must have a value.");
            return;
        }
        try
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            command.CommandText = "INSERT INTO Provinces (name) VALUES ('" + txtName.Text + "')";

            command.ExecuteNonQuery();
            MessageBox.Show("Data Saved");
            connection.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show("Error: " + ex);
        }
    }

    private void btnNewRecord_Click(object sender, EventArgs e)
    {
        txtID.Text = "";
        txtName.Text = "";
    }

    private void btnEdit_Click(object sender, EventArgs e)
    {
        if (txtID.Text == "")
        {
            MessageBox.Show("The id field must have a value.");
            return;
        }
        if(txtName.Text == "")
        {
            MessageBox.Show("The name field must have a value.");
            return;
        }
        try
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            command.CommandText = "UPDATE Provinces SET name='" + txtName.Text + "' WHERE id=" + txtID.Text + ";";

            command.ExecuteNonQuery();
            MessageBox.Show("Data Update Successful.");
            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex);
        }
    }

    private void btnDelete_Click(object sender, EventArgs e)
    {
        if (txtID.Text == "")
        {
            MessageBox.Show("The id field must have a value.");
            return;
        }
        try
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            command.CommandText = "DELETE FROM Provinces WHERE id=" + txtID.Text + ";";

            command.ExecuteNonQuery();
            MessageBox.Show("Record Deleted Successfully.");
            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex);
        }
    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if(e.RowIndex >= 0)
        {
            DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
            txtID.Text = row.Cells[0].Value.ToString();
            txtName.Text = row.Cells[1].Value.ToString();
        }
    }
}

      

}

+3


source to share


1 answer


This is a common scenario with a file-based database (or database attachments).
The connection string refers to the database without using any path. This means that your database is in the same directory where your application is running.
You have no problem inserting, modifying, or deleting data, but you lose everything when you reload your application from an INSIDE Visual Studio debug session.

Now, if you look at your project files, you probably have a database file listed between other files. Between the properties of this database file, you will see a property Copy to the Output directory

and its value is set to Copy Always

.

This means that every time you restart the application from Visual Studio, this file is copied from the project folder to the output directory (usually BIN \ DEBUG or BIN \ x86 \ DEBUG), but this destroys the database used in the previous run of deleting inserted data or deletion



Change the property Copy to Output Directory

to Copy Never

orCopy if Newer

However, it Copy if Newer

presents another problem with MS-Access. If you open a database file located in the project directory using Access o using the Connect to Server window in Visual Studio, the file is immediately modified unless you change anything and thus Copy If Newer will make a copy on output catalog

+3


source







All Articles