using System;
using System.Windows.Forms;
public class Form1 : Form
{
private DataGridView DataGridView1 = new DataGridView();
private Button PasteButton = new Button();
private TextBox TextBox1 = new TextBox();
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new Form1());
}
public Form1()
{
this.DataGridView1.AllowUserToAddRows = false;
this.DataGridView1.Dock = DockStyle.Fill;
this.Controls.Add(this.DataGridView1);
this.PasteButton.Text = "paste selected cells";
this.PasteButton.Dock = DockStyle.Top;
this.PasteButton.Click += new EventHandler(PasteButton_Click);
this.Controls.Add(this.PasteButton);
this.TextBox1.Multiline = true;
this.TextBox1.Height = 100;
this.TextBox1.Dock = DockStyle.Bottom;
this.Controls.Add(this.TextBox1);
this.Load += new EventHandler(Form1_Load);
this.Text = "DataGridView Clipboard demo";
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Initialize the DataGridView control.
this.DataGridView1.ColumnCount = 5;
this.DataGridView1.Rows.Add(new string[] { "A", "B", "C", "D", "E" });
this.DataGridView1.Rows.Add(new string[] { "F", "G", "H", "I", "J" });
this.DataGridView1.Rows.Add(new string[] { "K", "L", "M", "N", "O" });
this.DataGridView1.Rows.Add(new string[] { "P", "Q", "R", "S", "T" });
this.DataGridView1.Rows.Add(new string[] { "U", "V", "W", "X", "Y" });
this.DataGridView1.AutoResizeColumns();
this.DataGridView1.ClipboardCopyMode =
DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
}
private void PasteButton_Click(object sender, System.EventArgs e)
{
if (this.DataGridView1
.GetCellCount(DataGridViewElementStates.Selected) > 0)
{
try
{
// Add the selection to the clipboard.
Clipboard.SetDataObject(
this.DataGridView1.GetClipboardContent());
// Replace the text box contents with the clipboard text.
this.TextBox1.Text = Clipboard.GetText();
}
catch (System.Runtime.InteropServices.ExternalException)
{
this.TextBox1.Text =
"The Clipboard could not be accessed. Please try again.";
}
}
}
}
转载于:http://hi.baidu.com/%CB%CE%D7%D3%BE%FD%BF%D5%BC%E4/blog/item/471d3cca751fb383c91768bb.html