user575219
user575219

Reputation: 2442

DataGridview not updating to DB

I am using winforms application with a datagridview. Problem :Trying to save the edited data in the database Code:

     private void FillData(string selectCommand)
        {
            SQLiteConnection conn = new SQLiteConnection(connString);
            dataGridView1.AutoGenerateColumns = true;
            string selectCommand = "select * from Table1";
            da = new SQLiteDataAdapter(selectCommand, connString);
            conn.Open();
            ds = new DataSet();
            SQLiteCommandBuilder commandBuilder = new SQLiteCommandBuilder(da);
            da.Fill(ds,"Design1");
            dataGridView1.DataSource = ds.Tables[0] ;
            dataGridView1.DataMember = "Design1";
      }
 private void btnSave_Click(object sender, EventArgs e)
        {
            SQLiteConnection conn = new SQLiteConnection(connString);
            try
            {

                dataGridView1.EndEdit();

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    ds.Tables[0].Rows[i].AcceptChanges();
                }

                da.Update(ds.Tables[0]);


            }
            catch (Exception ex)
            {

                throw ex;
            }

        }

Not sure if this is an issue with Sqlite. There are no errors, except it does not update in the DB. Once I stop the application and reload it, edits are saved in DB.

Thank you Sun

Upvotes: 0

Views: 3497

Answers (1)

Steve
Steve

Reputation: 216353

I think you should reverse the order of AcceptChanges and Update lines

            dataGridView1.EndEdit(); 
            da.Update(ds.Tables[0]); 
            // Just accept on the table, no need to do row by row
            ds.Tables[0].AcceptChanges();

See the Remarks here for a reference

Let me say also, keeping all that vars around is not a good practice.
They could introduce side effects and bugs difficult to track.
In special mode, the connection should be disposed as fast as possible, encapsulanting in a using statement. (Provided that you explicity request the connection pooling feature -> "Pooling=True;Max Pool Size=100;")

For example:

     private void SaveData(DataGridView dgv, string selectCommand)  
     {  
        using(SQLiteConnection conn = new SQLiteConnection(connString))
        {
            conn.Open(); 
            SQLiteDataAdapter da = new SQLiteDataAdapter(selectCommand, connString); 
            SQLiteCommandBuilder commandBuilder = new SQLiteCommandBuilder(da); 
            DataTable dt = dgv.DataSource as DataTable;
            da.Update(dt);
            dt.AcceptChanges();
        }
     }

Upvotes: 2

Related Questions