I'm not asking how to copy a datagrid to my clipboard, but more of optimization of my code.
This is what I have to copy my datagridview to my clipboard so I can paste it's contents in excel.
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 &= oCurrentCol.HeaderText & 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 &= 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 &= row.Cells(oCurrentCol.Index).Value.ToString
End If
s &= 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 &= Environment.NewLine
Next 'Put to clipboard
Dim o As New DataObject
o.SetText(s)
Clipboard.SetDataObject(o, True)
This works great! Does exactly what I want it do, including leaving out the first column, and looks perfect when pasted into excel.
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.
I don't know what I could do to speed the process up. Any help is appreciated!
Thanks!