title: Delete selected datatable row from database
body: <p>I have a datatable in a DataGridView in C#. I filled this table with values obtained from a MySql database. Right now it can successfully retrieves the database table and adds to it once I added any new values to the datatable on WinForm side. This is the code for this purpose:</p>
  
  <pre><code>dbDataset.RowChanged += new DataRowChangeEventHandler(Row_Changed); // dbDataset is my datatable name
  </code></pre>
  
  <p>and </p>
  
  <pre><code>    private static void Row_Changed(object sender, DataRowChangeEventArgs e)
      {
              // here sda is my MySqlDataAdapter
              try
              {
                  MySqlCommandBuilder cmdb = new MySqlCommandBuilder(sda);
                  dbDataset.GetChanges();
                  dbDataset.GetChanges(DataRowState.Added);
                  dbDataset.GetChanges(DataRowState.Deleted);
                  dbDataset.GetChanges(DataRowState.Detached);
                  dbDataset.GetChanges(DataRowState.Modified);
                  dbDataset.GetChanges(DataRowState.Unchanged);                    
                  sda.Update(dbDataset);                
              }
              catch (Exception ex)
              {
                  MessageBox.Show(ex.Message);
              }
      }
  </code></pre>
  
  <p>But now I found that when I want to delete any row from the table, for instance I select a row and press "delete" key, it shows on the screen that it is deleted, but once I reload my WinForm, it still is there. Obviously it didn't delete that selected row from the database. For that, after some search, I added these parts:</p>
  
  <pre><code>dbDataset.RowDeleted += new DataRowChangeEventHandler(Row_Deleted);
  </code></pre>
  
  <p>and</p>
  
  <pre><code>    private static void Row_Deleted(object sender, DataRowChangeEventArgs e)
      {
          dbDataset.AcceptChanges();
      }
  </code></pre>
  
  <p>By debugging, I found that when I press "delete" key, it enters the <code>Row_Delete</code> function, then to <code>Row_Changed</code> function, but throws an exception, saying:</p>
  
  <pre><code>Additional information: Concurrency violation: the DeleteCommand affected 0 of the expected 1 records.
  </code></pre>
  
  <p>I searched to get the current row index of selection, so that I could use DataRow.delete method like:</p>
  
  <pre><code>CurrencyManager xCM = = (CurrencyManager)this.BindingContext[this.dataGridView1.DataSource, this.dataGridView1.DataMember];
  </code></pre>
  
  <p>and in the <code>Row_Deleted</code> function I added: </p>
  
  <pre><code>DataRowView xDRV = (DataRowView)xCM.Current;
  DataRow xDR = ((DataRowView)xCM.Current).Row;
  xDR.Delete();
  </code></pre>
  
  <p>but it gives out null exception, saying the datasource of dataGridView1 cannot be null. </p>
  
  <p>Is there any idea for how to delete the selected row from database? Thanks in advance. </p>