DevExpress的TreeList实现节点上添加自定义右键菜单并实现删除节点功能
程序员文章站
2022-06-24 08:14:48
场景 Winform控件-DevExpress18下载安装注册以及在VS中使用: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/100061243 DevExpress的TreeList怎样设置数据源,从实例入手: https:/ ......
场景
winform控件-devexpress18下载安装注册以及在vs中使用:
https://blog.csdn.net/badao_liumang_qizhi/article/details/100061243
devexpress的treelist怎样设置数据源,从实例入手:
https://blog.csdn.net/badao_liumang_qizhi/article/details/102548490
实现了树形结构后,我们要实现在树形节点上点击右键时弹窗,弹窗确认之后实现将当前节点删除。
注:
博客主页:
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
这里在窗体加载完的事件里绑定treelist的鼠标点击事件。
this.treelist2.mouseclick += treelist2_mouseclick;
在事件方法中
private void treelist2_mouseclick(object sender, mouseeventargs e) { //获取当前treelist对象 devexpress.xtratreelist.treelist treelist = sender as devexpress.xtratreelist.treelist; if (treelist != null && treelist.selection.count == 1) { object idvalue = null; string stridvalue = string.empty; datatreenode nodedata = null; //通过treelist的datasource属性获取所有节点的list list<datatreenode> datasource = treelist.datasource as list<datatreenode>; if (datasource != null) { //获取选中节点的集合中第一个的id属性 idvalue = treelist.selection[0].getvalue("id"); stridvalue = idvalue.tostring(); //获取当前选中节点datatreenode对象 nodedata = datasource.where<datatreenode>(p => p.id == stridvalue).firstordefault<datatreenode>(); if (nodedata != null) { //获取或设置是否启用聚焦节点的外观设置 -启用整行选中 treelist.optionsselection.enableappearancefocusedrow = true; //启用整行选中 #region 右键弹出上下文菜单 - 删除待比较的文件 //如果点击的是鼠标右键 if (e.button == system.windows.forms.mousebuttons.right) { //构建右键菜单 system.windows.forms.contextmenu ctxmenu = new system.windows.forms.contextmenu(); //构建右键删除菜单项 system.windows.forms.menuitem mnudelete = new system.windows.forms.menuitem(); mnudelete.text = "删除当前文件"; //删除菜单项点击事件订阅 mnudelete.click += delegate(object s, eventargs ea) { //devexpress的对话框 dialogresult dialogresult = devexpress.xtraeditors.xtramessagebox.show(string.format("确定要删除此实验数据吗[{0}]?\r\n删除后无法恢复!", nodedata.id), "标题", system.windows.forms.messageboxbuttons.yesno, messageboxicon.question); //如果点击了yes if (dialogresult == dialogresult.yes) { try { string filename = string.empty; #region 删除对应的树节点 //通过设置主键id找到节点node devexpress.xtratreelist.nodes.treelistnode selectednode = treelist.findnodebykeyid(nodedata.id); if (selectednode != null) { //删除节点 this.treelist2.nodes.remove(selectednode); } #endregion //禁用整行选中 treelist.optionsselection.enableappearancefocusedrow = false; } catch (exception ex) { icsharpcode.core.loggingservice<datatreelisthelper>.error("删除实验数据异常:" + ex.message, ex); devexpress.xtraeditors.xtramessagebox.show("删除实验数据异常:" + ex.message, "标题",messageboxbuttons.ok, messageboxicon.error); } } }; ctxmenu.menuitems.add(mnudelete); ctxmenu.show(treelist, new system.drawing.point(e.x, e.y)); } #endregion return; } } treelist.optionsselection.enableappearancefocusedrow = false; //禁用整行选中 } }
具体注释见代码。