How can I automatically update SQL when using DataGridView
I have figured out how to update SQL when using the DataGridView, but the only way that I can do it is with the use of a button. I want to do it after data has changed (added/edited/removed).
The RowsRemoved event seems to work alright, but I can't get the update to work after the CellValueChanged. I have posted my source. Any ideas how to get this working without having to press a button?
Thanks,
public frmUpdateComboOptions() { InitializeComponent(); conn.ConnectionString = connectionString; conn.Open(); string sql = "SELECT * FROM lookupSource"; da = new SqlDataAdapter(sql, conn); userTable = new DataTable(); da.Fill(userTable); conn.Close(); //SQL Command Builder for Updates and Deletes cb = new SqlCommandBuilder(da); //Apply DataSet to DataGridView control dgvSource.DataSource = null; dgvSource.AutoGenerateColumns = false; dgvSource.DataSource = userTable; //Sql Loaded bolSQLLoaded = true; } //Public Variables //============================================================= private string connectionString = "Data Source=WIN7-PC;Initial Catalog=TestDB;Integrated Security=SSPI;"; SqlConnection conn = new SqlConnection(); DataTable userTable; SqlDataAdapter da = new SqlDataAdapter(); DataRow LastDataRow = null; SqlCommandBuilder cb; bool bolSQLLoaded = false; //============================================================= private void UpdateRowToDatabase() { da.Update(userTable); } private void button1_Click(object sender, EventArgs e) { UpdateRowToDatabase(); } private void dgvSource_CellValueChanged(object sender, DataGridViewCellEventArgs e) { Debug.Print ("\n"); if (bolSQLLoaded == true) { Debug.Print("Updating DB - Cell Change"); dgvSource.UpdateCellValue(e.ColumnIndex, e.RowIndex); UpdateRowToDatabase(); } } private void dgvSource_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) { Debug.Print("\n"); if (bolSQLLoaded == true) { Debug.Print("Updating DB - Row Removed at: " + e.RowIndex.ToString()); da.Update(userTable); } }