-1

Hope someone can help with this. The following code is meant to add an entry to a Table; however, whilst the data is added at runtime, when the app is closed it disappears. The Database is set to 'Copy if Newer'.

   private void AddToNameList()
        {
            SqlConnection con = new SqlConnection(connectionString);

            cmd = new SqlCommand("INSERT INTO NameSurname VALUES (@NameId, @Surname)", con);
     
            cmd.Parameters.AddWithValue("@NameId", textBox2.Text);

            cmd.Parameters.AddWithValue("@Surname", textBox3.Text);
            con.Open();
            int i= cmd.ExecuteNonQuery();
            con.Close();
            if (i != 0)
            {
                MessageBox.Show(i + "Data Saved");
            }
            textBox2.Clear();
            textBox3.Clear();

        }

         private void button1_Click(object sender, EventArgs e)
        {
            if(textBox2.Text!= ("") && textBox3.Text!=(""))
            {
                AddToNameList();
            }
            else
            {
                MessageBox.Show("Please enter Name and Surname","Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

The message box confirms that the data is saved, and when I carry out a search it is there. However, when I stop the app running and check the database, the data is not there.

Grateful for any help.

Thanks

Dragon
  • 1
  • 1
  • You're overwriting your database file (which I assume is Sql Express or something like that) on each build of the application? – gunr2171 Feb 24 '21 at 22:19
  • It seems that this is what is happening, but I do not know why. I am using Visual Studio – Dragon Feb 24 '21 at 22:33
  • "The Database is set to 'Copy if Newer'." Don't do that. Either keep the database file away from the bin directory or don't overwrite it. – gunr2171 Feb 24 '21 at 22:34
  • My understanding was that the 'Copy if Newer' setting on the *mdf file ensured that changes to a database or a file persisted between builds. 'Do not copy' does not work. – Dragon Feb 24 '21 at 22:41
  • Do you have AttachDbFilename in the connection string? By the way you should be disposing the connection and command with `using` – Charlieface Feb 24 '21 at 22:41
  • I am using connectionString = `ConfigurationManager.ConnectionStrings["TheGrids.Properties.Settings.Database1ConnectionString"].ConnectionString;` to obtain the connection string form the App.config file. The connection string there has AttachDBFilename – Dragon Feb 24 '21 at 22:47
  • Does this answer your question? [what's the issue with AttachDbFilename](https://stackoverflow.com/questions/11178720/whats-the-issue-with-attachdbfilename) – Charlieface Feb 24 '21 at 23:12

1 Answers1

1

If you want to read a .mdf file, you must install SQL Server Express or SqlLocalDb runtime. Not all the other users are willing to download and install them.

To save the table to a database, I think SQLite will be a better choice.

Hope the following steps can help you.

First, install System.Data.SQLite using NuGet.

Second, configure the connection string in App.config.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
...
  <connectionStrings>
     <add name="SQLiteDbContext" connectionString="Data Source=MyDatabase.sqlite" providerName="System.Data.SQLite.EF6" />
  </connectionStrings>
</configuration>

Third, you can use the following code to create/insert/read the database/datatable.

// create
SQLiteConnection.CreateFile("MyDatabase.sqlite");
SQLiteConnection con = new SQLiteConnection("Data Source=MyDatabase.sqlite");
con.Open();
string sql = "create table NameSurname (Nameid varchar(20), Surname varchar(20))";
SQLiteCommand command = new SQLiteCommand(sql, con);
command.ExecuteNonQuery();
// insert
SQLiteCommand cmd = new SQLiteCommand("INSERT INTO NameSurname VALUES (@NameId, @Surname)", con);
cmd.Parameters.AddWithValue("@NameId", textBox2.Text);
cmd.Parameters.AddWithValue("@Surname", textBox3.Text);
cmd.ExecuteNonQuery();
// read
SQLiteCommand sqlCom = new SQLiteCommand("Select * From NameSurname", con);
SQLiteDataReader sqlDataReader = sqlCom.ExecuteReader();
int i = 1;
while (sqlDataReader.Read())
{
    listBox1.Items.Add(i);
    listBox1.Items.Add(sqlDataReader.GetValue(0));
    listBox1.Items.Add(sqlDataReader.GetValue(1));
    i++;
}
con.Close();
大陸北方網友
  • 3,696
  • 3
  • 12
  • 37
  • Many thanks for the input. I have tried this, but I still do not understand why Visual Studio 2019 allows me to create a table in a local database, make additions to it when the app is running, (they now remain even if I restart the app), but I cannot see the additions to the Table when I click on show table. I can only see additions I entered manually when I was testing a query. Any ideas? – Dragon Feb 25 '21 at 23:48