C#winform TreeViewでcheckbox選択に関する完璧なクラス
3330 ワード
public static class TreeViewCheck
{
/// <summary>
/// Checked
/// </summary>
/// <param name="e"></param>
public static void CheckControl(TreeViewEventArgs e)
{
if (e.Action != TreeViewAction.Unknown)
{
if (e.Node != null && !Convert.IsDBNull(e.Node))
{
CheckParentNode(e.Node);
if (e.Node.Nodes.Count > 0)
{
CheckAllChildNodes(e.Node, e.Node.Checked);
}
}
}
}
#region
//
private static void CheckAllChildNodes(TreeNode pn, bool IsChecked)
{
foreach (TreeNode tn in pn.Nodes)
{
tn.Checked = IsChecked;
if (tn.Nodes.Count > 0)
{
CheckAllChildNodes(tn, IsChecked);
}
}
}
// , ,
private static void CheckParentNode(TreeNode curNode)
{
bool bChecked = false;
if (curNode.Parent != null)
{
foreach (TreeNode node in curNode.Parent.Nodes)
{
if (node.Checked)
{
bChecked = true;
break;
}
}
if (bChecked)
{
curNode.Parent.Checked = true;
CheckParentNode(curNode.Parent);
}
else
{
curNode.Parent.Checked = false;
CheckParentNode(curNode.Parent);
}
}
}
#endregion
}
呼び出し方法:treeviewのAfterCheckイベントで
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) { TreeViewCheck.CheckControl(e)
}