111,097
社区成员




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.";
}
}
}
}
dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Visible)
/// <summary>
/// 计算GridView中的记录数
/// </summary>
/// <param name="gv">GridView的实例</param>
/// <returns></returns>
static public int GetRecordCount(GridView gv)
{
// 不分页,或只有1页,则取当前页的行数
if (!gv.AllowPaging || gv.PageCount <= 1)
return gv.Rows.Count;
// 记录当前页索引,以便计算完成后恢复
int nCurPage = gv.PageIndex;
// 跳转到最后一页
gv.PageIndex = gv.PageCount - 1;
gv.DataBind();
// 计算总行数,为:(总页数 - 1) * 每页行数 + 最后一页行数
int nTotalCount = gv.PageIndex * gv.PageSize + gv.Rows.Count;
// 恢复原页索引
gv.PageIndex = nCurPage;
gv.DataBind();
// 返回计算出的页数
return nTotalCount;
}