C# DataGridView组件自动添加弹出菜单(ContextMenuStrip)复制单元格的值
作者:C/S框架网|www.cscode.ne  发布日期:2021-05-30 18:15:19
  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




使用方法:



C# Code:

DataGridViewTool.Registe(gvData);

//来源:C/S框架网 | www.csframework.com | QQ:23404761





C/S框架网|原创精神.创造价值.打造精品

扫一扫加微信
C/S框架网作者微信 C/S框架网|原创作品.质量保障.竭诚为您服务




上一篇 下一篇