title: Deleting selected row from DataTable bound DataGridView
body: <p>Consider a <code>DataGridView</code> whose <code>DataSource</code> is a <code>DataTable</code>. The dataGridView allows one row to be selected at a time. There is a &quot;delete&quot; button, which should delete the selected rows, by one of the columns, from the bound dataTable.</p>
  <p>I have configured the <code>DataGridView</code> to be uneditable, from the user's point of view. It should only be possible to delete a row (from the dataTable and the grid) via a separate &quot;delete&quot; <code>Button</code> I have created. The event handler for this is shown below:</p>
  <pre><code>private void delete_Click(object sender, EventArgs args)
  {
  var usersTable = myGridView.DataSource as DataTable;
              foreach (DataGridViewRow selected in myGridView.SelectedRows)
              {
                  string name = (string)selectedRow.Cells[0].Value;
                  foreach (DataRow tableRow in usersTable.Rows)
                  {
                      if (tableRow[&quot;Name&quot;].ToString().Equals(name))
                          tableRow.Delete();
                  }
                  usersTable.AcceptChanges();
              }
  
              myGridView.DataSource = usersTable;
  }
  </code></pre>
  <p>How to does this properly, without &quot;collection was modified, enumeration might not execute&quot; errors?</p>
  <p>The grid is being populated as follows:</p>
  <pre><code>private DataTable usersTable = new DataTable(&quot;Users&quot;);
  
  void Populate()
  {
      usersTable.Columns.Clear();
      usersTable.Rows.Clear();
      usersTable.Columns.Add(&quot;Name&quot;, typeof(string));
      // addd other columns...
  
      foreach (var user in usersCollection)
      {
          usersTable.Rows.Add(user.GetName()),
          // add other rows...
      }
  
      // bind the data
      myGridView.DataSource = usersTable;
  }
  </code></pre>