DataGridView右键菜单自定义显示及隐藏列功能(2)

/// <summary> /// DataGridView右键菜单自定义显示及隐藏列 /// </summary> class DataGridViewColumnSelector { private DataGridView dgvTarget = null; //待处理的DataGridView对象 private ToolStripDropDown dropDown; //用于加载PopupMenu控件 PopupMenuControl popupMenuControl = new PopupMenuControl(); //PopupMenu控件 //无参构造函数 public DataGridViewColumnSelector() { //注册PopupMenu控件事件 popupMenuControl.CheckedChangedEvent += new PopupMenuControl.CheckedChanged(OnCheckedChanged); //使用容器承载PopupMenu控件(相当于容器类型的ToolStripItem) ToolStripControlHost controlHost = new ToolStripControlHost(popupMenuControl); controlHost.Padding = Padding.Empty; controlHost.Margin = Padding.Empty; controlHost.AutoSize = false; //加载PopupMenu控件 dropDown = new ToolStripDropDown(); dropDown.Padding = Padding.Empty; dropDown.AutoClose = true; dropDown.Items.Add(controlHost); } //有参构造函数 public DataGridViewColumnSelector(DataGridView dataGridView) : this() { DataGridView = dataGridView; } //DataGridView属性 public DataGridView DataGridView { get { return dgvTarget; } set { //去除单元格点击事件 if (dgvTarget != null) { dgvTarget.CellMouseClick -= new DataGridViewCellMouseEventHandler(DataGridView_CellMouseClick); } dgvTarget = value; //注册单元格点击事件 if (dgvTarget != null) { dgvTarget.CellMouseClick += new DataGridViewCellMouseEventHandler(DataGridView_CellMouseClick); } } } /// <summary> /// 右键点击标题栏弹出菜单 /// </summary> /// <param></param> /// <param></param> private void DataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Right && e.RowIndex == -1) { popupMenuControl.Initialize(dgvTarget); //将菜单显示在光标位置 dropDown.Show(Cursor.Position); } } /// <summary> /// 勾选事件执行方法 /// </summary> /// <param></param> /// <param></param> private void OnCheckedChanged(int hitIndex, bool isChecked) { dgvTarget.Columns[hitIndex].Visible = isChecked; } }

6、以上这些,已经实现了全部的功能。下面开始建一个WinForm程序来测试结果,为方便测试将DataGridView的数据源由xml文件读取。

从SQL Server数据库随便找张数据表生成XML,文件保存为Test.xml。(请将Test.xml文件拷贝到Debug文件夹下面)

SELECT TOP 10 MO_NO,MRP_NO,QTY,BIL_NO FROM MF_MO WHERE MO_DD='2019-11-07' ORDER BY MO_NO FOR XML PATH ('Category'),TYPE,ROOT('DocumentElement')

7、新建一个WinForm程序,命名为Main,并拖入一个DataGridView控件,Main_Load方法如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdswzj.html