C# DataGridView组件自动添加弹出菜单(ContextMenuStrip)复制单元格的值
C# DataGridView组件自动添加弹出菜单(ContextMenuStrip)复制单元格的值
扫一扫加微信
C# Code:
/// <summary>
/// DataGridView组件工具类
/// </summary>
public class DataGridViewTool
{
/// <summary>
/// 注册DataGridView组件,自动添加弹出菜单
/// </summary>
/// <param name="gv">DataGridView组件</param>
public static void Registe(DataGridView gv)
{
if (gv.ContextMenuStrip == null)
gv.ContextMenuStrip = new ContextMenuStrip();
//避免重复添加
var menu = gv.ContextMenuStrip.Items.Find("menuCopyCell", true);
if (menu.Length == 0)
{
ToolStripItem menuCopyCell = new ToolStripMenuItem("复制单元格");
menuCopyCell.Name = "menuCopyCell";
menuCopyCell.Click += MenuCopyCell_Click;
menuCopyCell.Tag = gv;
gv.ContextMenuStrip.Items.Add(menuCopyCell);
}
}
private static void MenuCopyCell_Click(object sender, EventArgs e)
{
ToolStripMenuItem menu = sender as ToolStripMenuItem;
if (menu.Tag != null)
{
DataGridView gv = menu.Tag as DataGridView;
//单元格选择
if (gv.SelectedCells != null && gv.SelectedCells.Count > 0)
Clipboard.SetText(gv.SelectedCells[0].Value.ToString());
//行模式,默认复制第1个单位格的资料
else if (gv.SelectedRows != null && gv.SelectedRows.Count > 0 && gv.SelectedRows[0].Cells.Count > 0)
Clipboard.SetText(gv.SelectedRows[0].Cells[0].Value.ToString());
}
}
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
/// DataGridView组件工具类
/// </summary>
public class DataGridViewTool
{
/// <summary>
/// 注册DataGridView组件,自动添加弹出菜单
/// </summary>
/// <param name="gv">DataGridView组件</param>
public static void Registe(DataGridView gv)
{
if (gv.ContextMenuStrip == null)
gv.ContextMenuStrip = new ContextMenuStrip();
//避免重复添加
var menu = gv.ContextMenuStrip.Items.Find("menuCopyCell", true);
if (menu.Length == 0)
{
ToolStripItem menuCopyCell = new ToolStripMenuItem("复制单元格");
menuCopyCell.Name = "menuCopyCell";
menuCopyCell.Click += MenuCopyCell_Click;
menuCopyCell.Tag = gv;
gv.ContextMenuStrip.Items.Add(menuCopyCell);
}
}
private static void MenuCopyCell_Click(object sender, EventArgs e)
{
ToolStripMenuItem menu = sender as ToolStripMenuItem;
if (menu.Tag != null)
{
DataGridView gv = menu.Tag as DataGridView;
//单元格选择
if (gv.SelectedCells != null && gv.SelectedCells.Count > 0)
Clipboard.SetText(gv.SelectedCells[0].Value.ToString());
//行模式,默认复制第1个单位格的资料
else if (gv.SelectedRows != null && gv.SelectedRows.Count > 0 && gv.SelectedRows[0].Cells.Count > 0)
Clipboard.SetText(gv.SelectedRows[0].Cells[0].Value.ToString());
}
}
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
使用方法:
C# Code:
DataGridViewTool.Registe(gvData);
//来源:C/S框架网 | www.csframework.com | QQ:23404761
//来源:C/S框架网 | www.csframework.com | QQ:23404761
扫一扫加微信
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网