private void LoadBookType()
{
//清空TreeView
tvBookType.Nodes.Clear();
//定义一个SortedList存储节点信息
SortedList objSortedList = new SortedList();
//遍历表格,把所有节点信息加载成一个树
for(int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["TypeId"].ToString() == "1")
{
TreeNode tn = new TreeNode();
tn.Text = dt.Rows[i]["TypeName"].ToString();
tn.Tag = dt.Rows[i]["TypeId"].ToString();
//根结点处于展开状态
tn.Expand();
//加载到SortedList中
objSortedList.Add(tn.Tag, tn);
//加载到TreeView控件中
tvBookType.Nodes.Add(tn);
}
else
{
//查找父结点
TreeNode parentNode = (TreeNode)objSortedList.GetByIndex(objSortedList.IndexOfKey(dt.Rows[i]["ParentTypeId"].ToString()));
//实例化子结点
TreeNode subNode = new TreeNode();
subNode.Text = dt.Rows[i]["TypeName"].ToString();
subNode.Tag = dt.Rows[i]["TypeId"].ToString();
//收起
subNode.Collapse();
//加载到SortedList中
objSortedList.Add(subNode.Tag, subNode);
//加载到Treeview控件父结点上
parentNode.Nodes.Add(subNode);
}
}
}
/// <summary>
/// 选择TreeView节点触发的事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tvBookType_AfterSelect(object sender, TreeViewEventArgs e)
{
TreeNode objTreeNode = tvBookType.SelectedNode;
//赋值
txtSubNodeId.Text = objTreeNode.Tag.ToString();
txtSubNodeName.Text = objTreeNode.Text;
//分类判断是否根结点
if (txtSubNodeId.Text == "1")//树根
{
txtParentNodeId.Text = "NULL";
txtParentNodeName.Text = string.Empty;
txtParentNodeId.Enabled = false;
txtParentNodeName.Enabled = false;
rtxtNodeDESC.Text = objBookTypeService.GetTypeDESC(Convert.ToInt32(txtSubNodeId.Text.Trim()));
}
else
{
Dictionary<int, string> parentDic = new Dictionary<int, string>();
parentDic=objBookTypeService.GetParentBookType(Convert.ToInt32(txtSubNodeId.Text.Trim()));
foreach (KeyValuePair<int,string> item in parentDic)
{
txtParentNodeId.Text = item.Key.ToString();
txtParentNodeName.Text =item.Value.ToString();
}
}
}
C#TreeView控件加载数据示例代码
最新推荐文章于 2021-08-17 10:51:32 发布