title: How to build a DataTable from a DataGridView?
body: <p>I may well be looking at this problem backwards but I am curious none the less.  Is there a way to build a <code>DataTable</code> from what is currently displayed in the <code>DataGridView</code>? </p>
  
  <p>To be clear, I know you can do this <code>DataTable data = (DataTable)(dgvMyMembers.DataSource);</code> however that includes hidden columns.  I would like to build it from the displayed columns only. </p>
  
  <p>Hope that makes sense.</p>
  
  <hr>
  
  <p>So I ended up trying a combination of a couple of answers as that seemed best.  Below is what I am trying.  Basically I am creating the DataTable from the DataSource and then working backwards based on if a column is visible or not.  However, after it removes a column I get a <code>Collection was modified; enumeration operation may not execute</code> on the next iteration of the <code>foreach</code>.  </p>
  
  <p>I am confused as I am not <strong><em>trying</em></strong> to modify the <code>DataGridView</code>, only the <code>DataTable</code> so what's up?</p>
  
  <pre><code>DataTable data = GetDataTableFromDGV(dgvMyMembers);
  
  
      private DataTable GetDataTableFromDGV(DataGridView dgv)
      {
          var dt = ((DataTable)dgv.DataSource).Copy();
          foreach (DataGridViewColumn column in dgv.Columns)
          {
              if (!column.Visible)
              {
                  dt.Columns.Remove(column.Name);
              }
          }
          return dt;
      }
  </code></pre>