Reputation: 1660
I have a simple data grid view and I am copying its content as below:
When i paste this to note pad, it appear as below:
How can i remove the blank line between 1 Jake and 3 Tom?
I am using this code to copy:
private void copySelectedToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.dataGridView1.GetCellCount(DataGridViewElementStates.Selected) > 0)
{
try
{
Clipboard.SetDataObject(
this.dataGridView1.GetClipboardContent());
}
catch (System.Runtime.InteropServices.ExternalException)
{
// "The Clipboard could not be accessed. Please try again.";
}
}
}
Is there is any better way to copy only selected? Please Help.
Upvotes: 2
Views: 8232
Reputation: 3476
You can loop over all selected rows:
string clipboard = "";
foreach (DataGridViewRow dgvr in dataGridView1.SelectedRows)
{
foreach (DataGridViewColumn dgvc in dg_autoTestStatus.Columns)
clipboard += dataGridView1.Rows[dgvr.Index].Cells[dgvc.Index].FormattedValue.ToString() + " ";
clipboard += "\n"
}
Clipboard.SetText(clipboard);
Upvotes: 0
Reputation: 2543
I'd solved it follows:
if (this.dataGridView1.SelectedRows.Count > 0)
{
StringBuilder ClipboardBuillder = new StringBuilder();
foreach (DataGridViewRow Row in dataGridView1.SelectedRows)
{
foreach (DataGridViewColumn Column in dataGridView1.Columns)
{
ClipboardBuillder.Append(Row.Cells[Column.Index].FormattedValue.ToString() + " ");
}
ClipboardBuillder.AppendLine();
}
Clipboard.SetText(ClipboardBuillder.ToString());
}
Upvotes: 3