Search code examples
c#sql-serverwinformsdatagridviewsqldatasource

.net 4 DataGridView does not update the database sqldatasource after adding, updating and deleting rows


I'm working on a big project and don't have much time to dwell on each problem, I'm using Windows Forms, particularly the DataGridView. I just added a data source that would query a table on the database. The enable add, delete, and edit properties are checked. I created this DataGridView through drag and drop, and adding a datasource. The query works fine when I run the program, the table appears on my DataGridView, I'm able to add, edit and delete rows on the DataGridView, but when I query the table through SQL Server Management Studio, the records in the table remain the same. What could be the problem?


Solution

  • I've found a solution. I've added a button named "Save Changes".

    First I make the initial declarations:

        private SqlDataAdapter da;
        private DataTable dt;
        private SqlCommandBuilder sqlCommandBuilder = null;
        private SqlConnection Con = new SqlConnection(@"Data Source=......");
    

    This is the Code for loading the DataGridView which populates it:

         private void DataGridView_Load(object sender, EventArgs e)
        {
    
            Con.Open();
            da = new SqlDataAdapter(@"SELECT * FROM tbl", Con);
            sqlCommandBuilder = new SqlCommandBuilder(da);
    
    
            dt = new DataTable(); 
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            Con.Close();
        }
    

    This is the code for the Save Changes button:

    private void button1_Click(object sender, EventArgs e)
        {
             SqlCommandBuilder local_SqlCommandBuilder = new SqlCommandBuilder(da);
    
                    local_SqlCommandBuilder.ConflictOption = System.Data.ConflictOption.OverwriteChanges;
    
                    da.UpdateCommand = local_SqlCommandBuilder.GetUpdateCommand();
    
                    da.Update(((System.Data.DataTable)this.dataGridView1.DataSource));
    
                    ((System.Data.DataTable)this.dataGridView1.DataSource).AcceptChanges();
    
        }