gpt4 book ai didi

C# 从列表框拖放到 TreeView

转载 作者:可可西里 更新时间:2023-11-01 08:36:19 25 4
gpt4 key购买 nike

我有一个带有列表框和 TreeView 的 winform。

一旦我的列表框充满了项目,我想将它们(多个或单个)从列表框中拖放到 TreeView 的一个节点中。

如果有人在 C# 中有一个很好的例子,那就太好了。

最佳答案

我已经有一段时间没有搞砸拖放了,所以我想我会写一个快速示例。

基本上,我有一个表单,左边是一个列表框,右边是一个 TreeView 。然后我在上面放了一个按钮。单击该按钮时,它只是将接下来十天的日期放入列表框中。它还使用 2 个父节点和两个子节点填充 TreeView。然后,您只需处理所有后续的拖放事件即可使其正常工作。

 public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.treeView1.AllowDrop = true;
this.listBox1.AllowDrop = true;
this.listBox1.MouseDown += new MouseEventHandler(listBox1_MouseDown);
this.listBox1.DragOver += new DragEventHandler(listBox1_DragOver);

this.treeView1.DragEnter += new DragEventHandler(treeView1_DragEnter);
this.treeView1.DragDrop += new DragEventHandler(treeView1_DragDrop);

}

private void button1_Click(object sender, EventArgs e)
{
this.PopulateListBox();
this.PopulateTreeView();
}

private void PopulateListBox()
{
for (int i = 0; i <= 10; i++)
{
this.listBox1.Items.Add(DateTime.Now.AddDays(i));
}
}

private void PopulateTreeView()
{
for (int i = 1; i <= 2; i++)
{
TreeNode node = new TreeNode("Node" + i);
for (int j = 1; j <= 2; j++)
{
node.Nodes.Add("SubNode" + j);
}
this.treeView1.Nodes.Add(node);
}
}

private void treeView1_DragDrop(object sender, DragEventArgs e)
{

TreeNode nodeToDropIn = this.treeView1.GetNodeAt(this.treeView1.PointToClient(new Point(e.X, e.Y)));
if (nodeToDropIn == null) { return; }
if(nodeToDropIn.Level > 0)
{
nodeToDropIn = nodeToDropIn.Parent;
}

object data = e.Data.GetData(typeof(DateTime));
if (data == null) { return; }
nodeToDropIn.Nodes.Add(data.ToString());
this.listBox1.Items.Remove(data);
}

private void listBox1_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}

private void treeView1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}

private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
this.listBox1.DoDragDrop(this.listBox1.SelectedItem, DragDropEffects.Move);
}


}

关于C# 从列表框拖放到 TreeView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/495666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com