DevExpress的TreeList实现节点上添加自定义右键菜单并实现删除节点功能

时间:2023-02-15 07:54:38


场景


实现了树形结构后,我们要实现在树形节点上点击右键时弹窗,弹窗确认之后实现将当前节点删除。

DevExpress的TreeList实现节点上添加自定义右键菜单并实现删除节点功能

 

注:

关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

这里在窗体加载完的事件里绑定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; //禁用整行选中
}
}

具体注释见代码。

DevExpress的TreeList实现节点上添加自定义右键菜单并实现删除节点功能