Dev TreeList基本用法
public partial class treelist_shijian : DevExpress.XtraEditors.XtraForm
{
public treelist_shijian()
{
InitializeComponent();
ShuJu();
}
//读取数据库绑定到treeList1中
public void ShuJu()
{
SqlConnection conn = new SqlConnection("server=(local);database=DEV_Test;Integrated Security=true;");
SqlCommand comm = new SqlCommand("select * from Table_treelist", conn);//select后面要写“*”否则树形结构的效果出不来
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
this.treeList1.DataSource = dt;
this.treeList1.KeyFieldName = "编号";
treeList1.ParentFieldName = "父类编号";
treeList1.Columns[0].Caption = "公司";
conn.Close();
//显示复选框
treeList1.OptionsView.ShowCheckBoxes = true;
}
//选择某一节点时,该节点的子节点全部选择 取消某一节点时,该节点的子节点全部取消选择
private void SetCheckedChildNodes(TreeListNode node, CheckState check)
{
for (int i = 0; i < node.Nodes.Count; i++)
{
node.Nodes[i].CheckState = check;
SetCheckedChildNodes(node.Nodes[i], check);
}
}
// 某节点的子节点全部选择时,该节点选择 某节点的子节点未全部选择时,该节点不选择
private void SetCheckedParentNodes(TreeListNode node, CheckState check)
{
if (node.ParentNode != null)
{
CheckState parentCheckState = node.ParentNode.CheckState;
CheckState nodeCheckState;
for (int i = 0; i < node.ParentNode.Nodes.Count; i++)
{
nodeCheckState = (CheckState)node.ParentNode.Nodes[i].CheckState;
if (!check.Equals(nodeCheckState))//只要任意一个与其选中状态不一样即父节点状态不全选
{
parentCheckState = CheckState.Unchecked;
break;
}
parentCheckState = check;//否则(该节点的兄弟节点选中状态都相同),则父节点选中状态为该节点的选中状态
}
node.ParentNode.CheckState = parentCheckState;
SetCheckedParentNodes(node.ParentNode, check);//遍历上级节点
}
}
//触发选择节点事件
private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
{
SetCheckedChildNodes(e.Node, e.Node.CheckState);
SetCheckedParentNodes(e.Node, e.Node.CheckState);
}
private List<string> lstCheckedOfficeID = new List<string>();//选择局ID集合
// 获取选择状态的数据主键ID集合
private void GetCheckedOfficeID(TreeListNode parentNode)
{
if (parentNode.Nodes.Count == 0)
{
return;//递归终止
}
foreach (TreeListNode node in parentNode.Nodes)
{
if (node.CheckState == CheckState.Checked)
{
DataRowView drv = treeList1.GetDataRecordByNode(node) as DataRowView;
if (drv != null)
{
string OfficeID = (string)drv["名称"];
lstCheckedOfficeID.Add(OfficeID);
}
}
GetCheckedOfficeID(node);
}
}
//查看哪些节点被选中
private void simpleButton1_Click(object sender, EventArgs e)
{
this.lstCheckedOfficeID.Clear();
if (treeList1.Nodes.Count > 0)
{
foreach (TreeListNode root in treeList1.Nodes)
{
GetCheckedOfficeID(root);
}
}
string idStr = string.Empty;
foreach (string id in lstCheckedOfficeID)
{
idStr += id + " ";
}
MessageBox.Show(idStr);
}
}
}