我在asp.net中使用Treeview 如果我选择任何父节点,那么它应该展开,其他父母应该在页面回发(导航)之后折叠......我正在使用下面的代码。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["TreeViewState"] != null)
{
List<string> list = (List<string>)Session["TreeViewState"];
RestoreTreeViewState(TreeViewApplicationSetup.Nodes, list);
}
}
else
{
List<string> list = new List<string>(100);
SaveTreeViewState(TreeViewApplicationSetup.Nodes, list);
Session["TreeViewState"] = list;
}
}
private void SaveTreeViewState(TreeNodeCollection nodes, List<string> list)
{
Session["TreeViewState"] = null;
foreach (TreeNode node in nodes)
{
if (node.ChildNodes != null)
{
if (node.Expanded.HasValue && node.Expanded == true && !String.IsNullOrEmpty(node.Text))
{
list.Add(node.Text);
}
if (node.ShowCheckBox == true && node.ChildNodes.Count == 0 && node.Parent.Expanded == true)
{
if (node.Checked == true)
{
list.Add(node.ValuePath + "-T");
}
else
{
list.Add(node.ValuePath + "-F");
}
}
SaveTreeViewState(node.ChildNodes, list);
}
}
}
private void RestoreTreeViewState(TreeNodeCollection nodes, List<string> list)
{
foreach (TreeNode node in nodes)
{
if (list.Contains(node.Text) || list.Contains(node.ValuePath + "-T") || list.Contains(node.ValuePath + "-F"))
{
if (node.ChildNodes != null && node.ChildNodes.Count != 0 && node.Expanded.HasValue && node.Expanded == false)
{
if (node.Parent != null)
{
if (list.Contains(node.ChildNodes[0].ValuePath + "T") || list.Contains(node.ChildNodes[0].ValuePath + "-F"))
{
node.Expand();
}
}
else
{
node.Expand();
}
}
else if (node.ChildNodes != null && node.Expanded.HasValue && node.Expanded == false)
{
if (node.ShowCheckBox == true && list.Contains(node.Parent.Text) && list.Contains(node.Parent.Parent.Text))
{
if (list.IndexOf(node.ValuePath + "-T") != -1)
{
node.Checked = true;
}
else if (list.IndexOf(node.ValuePath + "-F") != -1)
{
node.Checked = false;
}
}
}
}
else
{
if (node.ChildNodes != null && node.ChildNodes.Count != 0 && node.Expanded.HasValue && node.Expanded == true)
{
node.Collapse();
}
}
if (node.ChildNodes != null && node.ChildNodes.Count != 0)
{
RestoreTreeViewState(node.ChildNodes, list);
}
}
}
它的jsut帮助我在每个回发中扩展父节点但是其他父节点没有崩溃....
答案 0 :(得分:3)
在.aspx文件中:
...
<asp:TreeView ID="Tree" runat="server" OnSelectedNodeChanged="Tree_SelectNodeChange">
...
然后在codebehind Page_Load中,您只需将数据绑定到TreeView,并在OnSelectedNodeChanged处理程序中,您需要折叠所有节点,然后展开所选节点及其所有父节点:
protected void Tree_SelectNodeChange(object sender, EventArgs e)
{
var tree = (TreeView)sender;
foreach (TreeNode node in tree.Nodes)
{
node.CollapseAll();
}
ExpandToRoot(tree.SelectedNode);
}
private void ExpandToRoot(TreeNode node)
{
node.Expand();
if (node.Parent != null)
{
ExpandToRoot(node.Parent);
}
}