ContextMenuStrip 扩展,反射添加、删除dataGridView.DataSource绑定后内容
最近在用dataGridView.DataSource,由于dataGridView.DataSource会绑定不同类型的数据,需要一个通用的删除、添加功能
添加了弹出菜单ContextMenuStrip后需要针对不同的类型数据添加“插入一行”、“删除选中行”等功能。
代码不多,写成了 ContextMenuStrip 的扩展
var obj = dataGridView.DataSource
var type = obj.GetType();
var properties = type?.GetProperties();
var itemProperties = properties
?.FirstOrDefault(p => p.Name == "Item");
var d = itemProperties.DeclaringType;//获取声明类型,也就是 BindList<T>
var methods = d.GetMethods();//再获取公共方法,调用 Add、RemoveAt等
foreach (var mth in methods)
{
if (mth.Name == "RemoveAt")
{
foreach (int index in removeIndexs.OrderByDescending(i => i))
mth.Invoke(obj, new object[] { index });
}
}
/// <summary>/// BindList 公共方法/// get_Count/// get_Item/// set_Item/// Add/// Clear/// CopyTo/// Contains/// GetEnumerator/// IndexOf/// Insert/// Remove/// RemoveAt/// Equals/// GetHashCode/// GetType/// ToString/// </summary>public static class ContextMenuStripExten{public static void AddItem_RemoveSelect(this ContextMenuStrip menu, Control removeCtl, string text = "删除全部选中行"){if (removeCtl is DataGridView || removeCtl is ListBox || removeCtl is CheckedListBox){var item = menu.Items.Add(text);item.Click += (s, e) =>{object obj = null;List<int> removeIndexs = new List<int>();if (removeCtl is DataGridView){var dv = (DataGridView)removeCtl;if (dv.SelectedRows?.Count == 0) return;foreach (DataGridViewRow row in dv.SelectedRows)removeIndexs.Add(row.Index);obj = dv.DataSource;}else if (removeCtl is ListBox){var box = (ListBox)removeCtl;if (box.SelectedIndices?.Count == 0) return;foreach (int index in box.SelectedIndices)removeIndexs.Add(index);obj = box.DataSource;}else if (removeCtl is CheckedListBox){var box = (CheckedListBox)removeCtl;if (box.SelectedIndices?.Count == 0) return;foreach (int index in box.SelectedIndices)removeIndexs.Add(index);obj = box.DataSource;}var type = obj.GetType();var properties = type?.GetProperties();var itemProperties = properties?.FirstOrDefault(p => p.Name == "Item");var d = itemProperties.DeclaringType;var methods = d.GetMethods();foreach (var mth in methods){if (mth.Name == "RemoveAt"){foreach (int index in removeIndexs.OrderByDescending(i => i))mth.Invoke(obj, new object[] { index });}}};}else if (removeCtl is TreeView){var tv = (TreeView)removeCtl;var item = menu.Items.Add(text);item.Click += (s, e) =>{if (tv.SelectedNode == null)return;if (tv.SelectedNode.Level > 0)tv.SelectedNode.Parent.Nodes.Remove(tv.SelectedNode);elsetv.Nodes.Remove(tv.SelectedNode);};}}public static void AddItem_InsertBeforSelect(this ContextMenuStrip menu, Control removeCtl, string text = "插入一行"){if (removeCtl is DataGridView || removeCtl is ListBox || removeCtl is CheckedListBox){var item = menu.Items.Add(text);item.Click += (s, e) =>{object obj = null;int selectedIndexs = 0;if (removeCtl is DataGridView){var dv = (DataGridView)removeCtl;if (dv.SelectedRows?.Count == 0) return;selectedIndexs = dv.SelectedRows[0].Index;obj = dv.DataSource;}else if (removeCtl is ListBox){var box = (ListBox)removeCtl;if (box.SelectedIndices?.Count == 0) return;selectedIndexs = box.SelectedIndex;obj = box.DataSource;}else if (removeCtl is CheckedListBox){var box = (CheckedListBox)removeCtl;if (box.SelectedIndices?.Count == 0) return;selectedIndexs = box.SelectedIndex;obj = box.DataSource;}var type = obj.GetType();var properties = type?.GetProperties();var itemProperties = properties?.FirstOrDefault(p => p.Name == "Item");var d = itemProperties.DeclaringType;var methods = d.GetMethods();foreach (var mth in methods){if (mth.Name == "Insert"){try{Assembly assembly = Assembly.GetExecutingAssembly(); // 获取当前程序集 dynamic instance = assembly.CreateInstance(itemProperties.PropertyType.FullName); // 创建类的实例,返回为 object 类型,需要强制类型转换mth.Invoke(obj, new object[] { selectedIndexs, instance });}catch { }}}};}else if (removeCtl is TreeView){var tv = (TreeView)removeCtl;var item = menu.Items.Add(text);item.Click += (s, e) =>{if (tv.SelectedNode == null)return;if (tv.SelectedNode.Level > 0)tv.SelectedNode.Parent.Nodes.Remove(tv.SelectedNode);elsetv.Nodes.Remove(tv.SelectedNode);};}}public static void AddItem_EditSelect(this ContextMenuStrip menu, Control removeCtl, string text = "批量修改选中格"){if (removeCtl is DataGridView || removeCtl is ListBox || removeCtl is CheckedListBox){var item = menu.Items.Add(text);item.Click += (s, e) =>{if (removeCtl is DataGridView){var dv = (DataGridView)removeCtl;var cells = dv.SelectedCells.Cast<DataGridViewCell>();if (!cells.All(c => c.RowIndex == cells.First().RowIndex)){var msg = string.Join("\r\n", cells.Select(c => $"{c.Value}\t{c.RowIndex}\t{c.ColumnIndex}"));if (MessageBox.Show($"所选格不在同一列,确定修改?\r\n内容\t行号\t列号\r\n{msg}", "确认修改", MessageBoxButtons.YesNo) == DialogResult.No)return;}var newValue = Interaction.InputBox("输入新内容");if (string.IsNullOrEmpty(newValue) && cells.Count() > 0 && MessageBox.Show($"新内容为空,确认修改?", "确认修改", MessageBoxButtons.YesNo) == DialogResult.No)return;foreach (var cell in cells){cell.Value = newValue;}}else if (removeCtl is ListBox){var box = (ListBox)removeCtl;if(box.SelectedIndices?.Count > 1){if (MessageBox.Show($"一共选中 {box.SelectedIndices?.Count } 行,确认修改?", "确认修改", MessageBoxButtons.YesNo) == DialogResult.No)return;}var newValue = Interaction.InputBox("输入新内容");if (string.IsNullOrEmpty(newValue) && box.SelectedIndices?.Count > 0 && MessageBox.Show($"新内容为空,确认修改?", "确认修改", MessageBoxButtons.YesNo) == DialogResult.No)return;foreach (int index in box.SelectedIndices){box.Items[index] = newValue;}}else if (removeCtl is CheckedListBox){var box = (CheckedListBox)removeCtl;if (box.SelectedIndices?.Count > 1){if (MessageBox.Show($"一共选中 {box.SelectedIndices?.Count } 行,确认修改?", "确认修改", MessageBoxButtons.YesNo) == DialogResult.No)return;}var newValue = Interaction.InputBox("输入新内容");if (string.IsNullOrEmpty(newValue) && box.SelectedIndices?.Count > 0 && MessageBox.Show($"新内容为空,确认修改?", "确认修改", MessageBoxButtons.YesNo) == DialogResult.No)return;foreach (int index in box.SelectedIndices){box.Items[index] = newValue;}}};}else if (removeCtl is TreeView){var tv = (TreeView)removeCtl;var item = menu.Items.Add(text);item.Click += (s, e) =>{if (tv.SelectedNode == null)return;var newValue = Interaction.InputBox("TreeNode 修改有三处需要修改:\r\nText\tName\tToolTipText\r\n用逗号隔开","输入新内容","节点文本,节点名,节点提示文本");if (string.IsNullOrEmpty(newValue) && MessageBox.Show($"新内容为空,确认修改?", "确认修改", MessageBoxButtons.YesNo) == DialogResult.No)return;var arr = newValue.Split(new char[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries);for(var i=0;i<arr.Length;i++){switch (i){case 0:tv.SelectedNode.Text = arr[i];break;case 1:tv.SelectedNode.Name = arr[i];break;case 2:tv.SelectedNode.ToolTipText = arr[i];break;}}};}}}
ContextMenuStrip 扩展,反射添加、删除dataGridView.DataSource绑定后内容相关推荐
- C# Winfrom DataGridView DataSource绑定数据源后--解决排序问题
C# Winfrom DataGridView DataSource绑定数据源后--解决排序问题 参考文章: (1)C# Winfrom DataGridView DataSource绑定数据源后-- ...
- [CentOS]添加删除用户
https://www.cnblogs.com/wolf-sun/p/CnetOs7-user.html 摘要 在安装CentOS的时候,我们只设置了root,类似windows的超级管理员.当然我们 ...
- 扩展JavaScript数组(Array)添加删除元素方法
为JavaScript数组(Array)扩展 添加删除元素方法 作者:jcLee95:https://blog.csdn.net/qq_28550263?spm=1001.2101.3001.5343 ...
- android仿微信发布动态功能,Android GridView扩展仿微信微博发图动态添加删除图片功能.pdf...
Android GridView扩扩展展仿仿微微信信微微博博发发图图动动态态添添加加删删除除图图片片功功能能 这篇文章主要为大家详细介绍了Android GridView扩展仿微信微博发图动态添加删除 ...
- js基础3 dom基础/绑定获取事件/图片切换练习/文档加载/全选全不选/dom的其他属性/dom的增加/添加删除练习
dom基础 <!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8 ...
- C# 删除DataGridView选中行
//普通删除方式 int i = dgvAwaitX.CurrentRow.Index; DataGridViewRow row = dgvAwaitX.Rows[i]; dgvAwaitX.Rows ...
- winform代码:关联窗体数据更新,删除dataGridview中选中的一行或多行
一.关联窗体数据更新 关联窗体数据修改时,如果一个为总体数据显示窗体A,另一个为详细修改窗体B,从A进入B,在B中对数据进行修改,然后返回A,这时A窗体的数据需要更新. 我采用最简单的方法,首先保证每 ...
- html 删除记录,添加删除记录.html
添加删除记录练习 window.onload = function () { var allA = document.getElementsByTagName("a"); //为删 ...
- JavaScript基础13-day15【DOM增删改、DOM添加删除记录、操作内联样式、获取元素的样式、DOM Element 对象、滚动条练习、事件对象、div跟随鼠标移动、事件冒泡】
学习地址: 谷粒学院--尚硅谷 哔哩哔哩网站--尚硅谷最新版JavaScript基础全套教程完整版(140集实战教学,JS从入门到精通) JavaScript基础.高级学习笔记汇总表[尚硅谷最新版Ja ...
最新文章
- R语言关系操作符:>、<=、!=、>=、==、
- Thymeleaf引用片段传入参数
- python——Web服务开发(二)分布式缓存
- 解决webstorm中vue语法没有提示
- SAP License:共享服务的今天和明天
- 2018杭州电子科技大学计算机研究生复试笔试编程题第三题
- 如何“在21天内自学C++”
- Gson反序列化详解
- vulkan sdk 下载地址
- Structs2.0.11.1升级到2.5.30
- ai怎么做盒子效果图_AI制作包装纸盒贴图教程
- 2021年全球排烟扇收入大约181百万美元,预计2028年达到198.7百万美元
- 多线程3——线程连接、分离和取消(linux)
- 西安财经大学计算机考研科目,西安财经大学2020年硕士研究生考试复试科目与参考书目...
- ubuntu返回图形界面_Ubuntu设置命令行界面和图形界面切换方法
- python中如何求水仙花数_python如何求水仙花数?
- python如何撤回_python如何查看微信消息撤回
- @RequiredArgsConstructor 代替@AutoWired注解
- 迷茫的vbs整人代码,把我整迷了
- 2018最新动脑学院数据结构与算法系列视频教程
热门文章
- android imagebutton 按下效果,网上看到一个自定义ImageButton按下效果的方法,来个大神来解疑...
- 【教学类-26-01】背诵家长电话号码-Python数字填空(中班 偏数学和社会)
- 如何清洁电脑键盘上的灰尘?
- 热释电系数测试中的正弦波温度控制解决方案:帕尔帖制冷片
- ABB_IRB120动力学仿真
- 次世代 php验证码识别,次世代验证码识别系统
- Android培训班(20)
- 喜力啤酒全球重磅推出全新包装
- 装饰装修企业痛点与分析-收款问题
- 京东消费行为数据分析可视化实战案例