gordon wrote:
Hi
I hav e a smallish app that has a datagridview. A user can select
some columns in the datagrid, and i have a button that i would like
to use to copy the rows that are selected to the clipboard or to a
text file.
Any ideas how to accomplish this?
I have all the controls working in this form apart from this feature.
Any sample code would be appreciated.
See DataGridView.SelectedCells, SelectedRows, SelectedColumns. Which one
you should use depends on how your selections are constrained (are they
always rows? always columns? arbitrary?)
The DataGridView won't help you format the data for clipboard use - that's
something you need to decide on an implement yourself. A good strategy for
grid data is to join together cells from the same row, separated with tabs,
then join together the rows with newlines. Put all of that data on the
clipboard using Clipboard.SetData. That format allows the data to be pasted
directly into Word or Excel and be recognized as a table.
For example, if your selections are always rows:
private void m_copyButton_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
// column headers
sb.Append("Col 1 Title\t");
sb.Append("Col 2 Title\t");
sb.Append("Col 3 Title\t");
sb.Append(Environment.NewLine);
// start concatenating the selected rows together
foreach (DataGridViewRow row in m_dataGridView.SelectedRows)
{
sb.AppendFormat("{0}\t",row.Cells[1].Value);
sb.AppendFormat("{0}\t",row.Cells[2].Value);
sb.AppendFormat("{0}\t",row.Cells[3].Value);
sb.Append(Environment.NewLine);
}
Clipboard.SetData(DataFormats.Text, sb.ToString());
}
-cd