我在我的Windows应用程序中有树视图,在树视图中有复选框,我有一些"父节点"和一些儿童节点"并且我想一次点击"全部检查"检查并取消检查父节点和子节点。和"取消选中所有"按钮......我该怎么做?
现在,如果我单击特定的父节点以及子文件夹,它应该在列表视图中显示它!
在这里输入代码
namespace howto_treeview_select_subtree
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
trvMeals.CheckBoxes = true;
foreach (TreeNode node in trvMeals.Nodes)
{
ExpandNode(node);
}
trvMeals.SelectedNode = trvMeals.Nodes[0];
foreach (TreeNode node in trvMeals.Nodes)
{
node.Checked = true;
}
}
private void ExpandNode(TreeNode node)
{
node.EnsureVisible();
foreach (TreeNode child in node.Nodes)
{
ExpandNode(child);
}
}
private void trvMeals_AfterCheck(object sender, TreeViewEventArgs e)
{
TreeNode node = e.Node;
bool is_checked = node.Checked;
foreach (TreeNode child in node.Nodes)
{
child.Checked = is_checked;
}
trvMeals.SelectedNode = node;
}
private void trvMeals_AfterSelect(object sender, TreeViewEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
foreach (TreeNode node in trvMeals.Nodes)
{
node.Checked = true;
CheckChildren(node, true);
}
//foreach (TreeNode node in trvMeals.Nodes)
//{
// node.Checked = true;
//}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (TreeNode node in trvMeals.Nodes)
{
node.Checked = false;
}
}
private void button3_Click(object sender, EventArgs e)
{
listView1.Text = (listView1 + "\n") + trvMeals.SelectedNode.Text;
//foreach (TreeNode node in trvMeals.Nodes)
//{
// RcTxt.Text = RcTxt.Text + trvMeals.SelectedNode.Text;
//}
}
private void CheckChildren(TreeNode rootNode, bool isChecked)
{
foreach (TreeNode node in rootNode.Nodes)
{
CheckChildren(node, isChecked);
node.Checked = isChecked;
}
}
private void button4_Click(object sender, EventArgs e)
{
listView1.Clear();
}
}
}
答案 0 :(得分:2)
执行此操作的一种方法是,您可以为AfterSelect
的{{1}}事件创建事件处理程序。
像这样的东西
TreeView
要执行检查和取消选中,请为private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) {
//grab the listView object and sender as TreeView.
//grab whatever you need from the TreeView
//Put whatever you need in the listView
}
事件TreeView
创建另一个事件处理程序。
AfterCheck
编辑:
扩展代码:
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) {
TreeView view = sender as TreeView;
//Access the treeview nodes, check/uncheck them
}
我已经扩展了代码,以便您有更好的想法。希望它可能有所帮助。
注意:我没有彻底检查代码,因为它可能需要一段时间,但我相信这应该足以让您获得必要的工具以及基本的想法。