我正在使用Windows窗体,并且我想按KeyDown
事件在剪贴板中设置的顺序复制整个树形视图及其子视图
首先,我尝试将父节点设置为:
private void tvProjectList_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.C))
{
var treeViewParents = "";
foreach (TreeNode tn in tvProjectList.Nodes)
{
treeViewParents += tn.Text + Environment.NewLine;
}
Clipboard.SetText(treeViewParents);
}
}
但是它只得到一个节点而不是所有节点。我应该怎么做?问候
更新:
为了得到Nodes及其孩子,我有
private void tvProjectList_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.C))
{
foreach (TreeNode node in tvProjectList.Nodes)
{
PrintNodesRecursive(node);
}
}
}
public void PrintNodesRecursive(TreeNode oParentNode)
{
Console.WriteLine(oParentNode.Text);
var treeViewParents = "";
StringBuilder sb = new StringBuilder();
// Start recursion on all subnodes.
foreach (TreeNode oSubNode in oParentNode.Nodes)
{
sb.Append(oSubNode.Text + Environment.NewLine);
PrintNodesRecursive(oSubNode);
}
Clipboard.SetText(sb.ToString());
}
但是字符串生成器总是带有空字符串...为什么数据没有保存在字符串生成器中?问候
答案 0 :(得分:2)
在我的评论中,这是一个递归方法的示例实现,以实现此目的:
private void CopyTreeViewToClipboard(TreeView treeView)
{
// Make a StringBuilder to store the text of each individual node
var treeViewStringBuilder = new StringBuilder();
// Initiate the recursive method
GetTreeViewNodesText(treeView.Nodes, treeViewStringBuilder);
// because StringBuilder is a reference type we do not need use a return value
// and we can copy to clipboard using the already existing reference
Clipboard.SetText(treeViewStringBuilder.ToString());
}
private void GetTreeViewNodesText(TreeNodeCollection nodesInCurrentLevel, StringBuilder sb, int level = 0)
{
foreach (TreeNode currentNode in nodesInCurrentLevel)
{
// Add some padding (spaces) in front to display the current level
sb.Append(new string(' ', level * 2));
// Add the text and terminate the line \n\r
sb.AppendLine(currentNode.Text);
// Recursion happens here, it's level + 1 instead of level++ because we
// do not want to alter the level for the next nodes in nodesInCurrentLevel
GetTreeViewNodesText(currentNode.Nodes, sb, level + 1);
}
}