title: Datagridview to Clipboard Optimization
body: <p>I'm not asking how to copy a datagrid to my clipboard, but more of optimization of my code.</p>
  
  <p>This is what I have to copy my datagridview to my clipboard so I can paste it's contents in excel.</p>
  
  <pre><code>    Dim dgv As DataGridView = dgvData
      Dim s As String = ""
      Dim oCurrentCol As DataGridViewColumn    'Get header
      oCurrentCol = dgv.Columns.GetFirstColumn(DataGridViewElementStates.Visible)
      oCurrentCol = dgv.Columns.GetNextColumn(oCurrentCol, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
  
      Do
          s &amp;= oCurrentCol.HeaderText &amp; Chr(Keys.Tab)
          oCurrentCol = dgv.Columns.GetNextColumn(oCurrentCol, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
      Loop Until oCurrentCol Is Nothing
  
      s = s.Substring(0, s.Length - 1)
      s &amp;= Environment.NewLine    'Get rows
      For Each row As DataGridViewRow In dgv.Rows
          oCurrentCol = dgv.Columns.GetFirstColumn(DataGridViewElementStates.Visible)
          oCurrentCol = dgv.Columns.GetNextColumn(oCurrentCol, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
          Do
              If row.Cells(oCurrentCol.Index).Value IsNot Nothing Then
                  s &amp;= row.Cells(oCurrentCol.Index).Value.ToString
              End If
              s &amp;= Chr(Keys.Tab)
              oCurrentCol = dgv.Columns.GetNextColumn(oCurrentCol, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
          Loop Until oCurrentCol Is Nothing
          s = s.Substring(0, s.Length - 1)
          s &amp;= Environment.NewLine
      Next    'Put to clipboard
  
      Dim o As New DataObject
      o.SetText(s)
      Clipboard.SetDataObject(o, True)
  </code></pre>
  
  <p>This works great! Does exactly what I want it do, including leaving out the first column, and looks perfect when pasted into excel.  </p>
  
  <p>Now the problem I'm having is it's extremely slow.  On my development computer, it will take almost two minutes to copy ~10,000 rows of 10 columns.  On some of our older servers I let it run from over ten minutes and eventually just killed the process because it was taking so long.</p>
  
  <p>I don't know what I could do to speed the process up. Any help is appreciated! </p>
  
  <p>Thanks!</p>