Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I want to save my data from datagridview to my SQLite database but there is some errors.

The data could not get saved into the database and the error message box keeps popping up

What I have tried:

SQLiteConnection sa = new SQLiteConnection("Data Source=|DataDirectory|\\trendchart.db");
           sa.Open();

           using (SQLiteConnection sqlconn = new SQLiteConnection(sa))
           {

               foreach (DataGridViewRow row in dataGridView1.Rows)
               {
                   for (int z = 0; z < 31; z++)

                   {
                       using (SQLiteCommand sqlcomm = sqlconn.CreateCommand())
                       {

                           sqlcomm.CommandText = "Insert into data (TOP(1),TOP(2) ) values(@TOP(1),@TOP(2))";
                           try
                           {
                               sqlcomm.Parameters.AddWithValue("TOP(1)", dataGridView1.CurrentRow.Cells["TOP(1)"].Value.ToString());
                               sqlcomm.Parameters.AddWithValue("TOP(2)", dataGridView1.CurrentRow.Cells["TOP(2)"].Value.ToString());
                               sqlcomm.ExecuteNonQuery();
                               MessageBox.Show("Data is save please check thks ");

                           }
                           catch (Exception ex)
                           {
                               MessageBox.Show("Error Please fix ");
                           }
                       }
                   }
Posted
Updated 5-Jul-18 1:28am
v2
Comments
Richard MacCutchan 5-Jul-18 5:25am    
What errors? Please do not expect us to guess what happens when you run your code, we cannot see your screen.

I'm pretty sure it's the way you've named your columns and your sql parameters. Try this instead
C#
sqlcomm.CommandText = "Insert into data ([TOP(1)],[TOP(2)] ) values(@TOP1,@TOP2)";
 try
 {
     sqlcomm.Parameters.AddWithValue("@TOP1", dataGridView1.CurrentRow.Cells["TOP(1)"].Value.ToString());
     sqlcomm.Parameters.AddWithValue("@TOP2", dataGridView1.CurrentRow.Cells["TOP(2)"].Value.ToString());
     sqlcomm.ExecuteNonQuery();
Points to Note:
- the square brackets around the column names - they'd be illegal otherwise.
- The @ symbols when adding the parameters
- Removal of the (illegal) characters in the parameter names - TOP(1) becomes @TOP1
 
Share this answer
 
v2
Comments
Richard Deeming 5-Jul-18 10:30am    
You've got one of the square brackets the wrong way round - [TOP(1)[ should be [TOP(1)]. :)
CHill60 5-Jul-18 10:58am    
D'oh - I'll fix that. Thanks
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900