数据库查询
id name id name
----------- ---------- ----------- ----------
1 饮料 4 可乐
1 饮料 5 雪碧
1 饮料 6 娃哈哈
2 烟酒 7 中华
2 烟酒 8 茅台
3 零食 9 唐僧肉
3 零食 10 卫龙
Model
public class TreeModel
{
public int id { get; set; }
public string name { get; set; }
public int parentId { get; set; }
}
设置数据源
private void Form1_Load(object sender, EventArgs e)
{
//开启复选框
treeList1.OptionsView.ShowCheckBoxes = true;
treeList1.OptionsBehavior.AllowIndeterminateCheckState = true;
treeList1.KeyFieldName = "id";
treeList1.ParentFieldName = "parentId";
treeList1.DataSource = GetAllData();
}
复选的各种事件 出处:https://www.cnblogs.com/yangykaifa/p/7077690.html
//节点选中前事件
private void treeList1_BeforeCheckNode(object sender, DevExpress.XtraTreeList.CheckNodeEventArgs e)
{
if (e.PrevState == CheckState.Checked)
{
e.State = CheckState.Unchecked;
}
else
{
e.State = CheckState.Checked;
}
}
//节点选中后事件
private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
{
SetCheckedChildNodes(e.Node, e.Node.CheckState);
SetCheckedParentNodes(e.Node, e.Node.CheckState);
}
/// <summary>
/// 设置子节点状态
/// </summary>
/// <param name="node"></param>
/// <param name="check"></param>
private void SetCheckedChildNodes(DevExpress.XtraTreeList.Nodes.TreeListNode node, CheckState check)
{
for (int i = 0; i < node.Nodes.Count; i++)
{
node.Nodes[i].CheckState = check;
SetCheckedChildNodes(node.Nodes[i], check);
}
}
/// <summary>
/// 设置父节点状态
/// </summary>
/// <param name="treeListNode"></param>
/// <param name="checkState"></param>
private void SetCheckedParentNodes(DevExpress.XtraTreeList.Nodes.TreeListNode treeListNode, CheckState checkState)
{
if (treeListNode.ParentNode != null)
{
bool b = false;
CheckState state;
for (int i = 0; i < treeListNode.ParentNode.Nodes.Count; i++)
{
state = (CheckState)treeListNode.ParentNode.Nodes[i].CheckState;
if (!checkState.Equals(state))
{
b = !b;
break;
}
}
if (b)
{
treeListNode.ParentNode.CheckState = CheckState.Indeterminate;
}
else
{
treeListNode.ParentNode.CheckState = checkState;
}
SetCheckedParentNodes(treeListNode.ParentNode, checkState);
}
}