在ASP.NET中,实现树形结构的多选功能需要一些额外的步骤。以下是一个简单的方法来实现这个功能:
public class TreeNode
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public bool IsSelected { get; set; }
public List<TreeNode> Children { get; set; }
public TreeNode()
{
Children = new List<TreeNode>();
}
}
TreeView
控件:<asp:TreeView ID="TreeView1" runat="server" OnTreeNodeCheckChanged="TreeView1_TreeNodeCheckChanged">
</asp:TreeView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
InitializeTree();
}
}
private void InitializeTree()
{
TreeNode rootNode = new TreeNode
{
Id = 1,
Name = "Root",
ParentId = null
};
TreeNode childNode1 = new TreeNode
{
Id = 2,
Name = "Child 1",
ParentId = 1
};
TreeNode childNode2 = new TreeNode
{
Id = 3,
Name = "Child 2",
ParentId = 1
};
rootNode.Children.Add(childNode1);
rootNode.Children.Add(childNode2);
TreeView1.Nodes.Add(rootNode);
}
protected void TreeView1_TreeNodeCheckChanged(object sender, TreeNodeCheckChangedEventArgs e)
{
TreeNode node = e.Node;
// 递归检查子节点
CheckChildNodes(node);
// 检查父节点
CheckParentNode(node);
}
private void CheckChildNodes(TreeNode node)
{
foreach (TreeNode childNode in node.Children)
{
childNode.Checked = node.Checked;
CheckChildNodes(childNode);
}
}
private void CheckParentNode(TreeNode node)
{
if (node.ParentId != null)
{
TreeNode parentNode = TreeView1.Nodes.FindByValue(node.ParentId);
if (parentNode != null)
{
parentNode.Checked = node.Checked;
CheckParentNode(parentNode);
}
}
}
现在,当你在树形结构中选择一个节点时,它的所有子节点也会被选中。你可以根据需要调整这个实现以满足你的需求。