简体   繁体   中英

Treeview parent node should select with its child node by default in Treeview

I have a treeview control with checkbox for each node.Each node represent a department. I want main department should be selected with its subdepartment by default. Below is the control code:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
   <ContentTemplate>
       <asp:LinkButton runat="server" ID="lnkSelectAllDepartments" Text="Select All" OnClick="lnkSelectAllDepartments_Click"  Font-Bold="false" Font-Underline="true"></asp:LinkButton>|
           <span class="labelText" style="font-weight:bold"> | </span>
              <asp:LinkButton runat="server" ID="lnkDeselectAllDepartments" Text="Deselect All" OnClick="lnkDeselectAllDepartments_Click"  Font-Bold="false" Font-Underline="true"></asp:LinkButton>
                  <br />
                  <br />
                      <asp:CheckBoxList ID="listDepartment" runat="server" Height="120px" RepeatDirection="Vertical" RepeatLayout="Flow"> </asp:CheckBoxList>
                      <asp:TreeView ID="tvDepartments" runat="server" ShowCheckBoxes="All" ShowExpandCollapse="true" ExpandDepth=0 NodeStyle-ForeColor="Black" ></asp:TreeView>
     </ContentTemplate>
</asp:UpdatePanel> 

And below code is for code behind:

/*Added for TreeView control...*/
string rootDepartmentName = ConfigurationReader.ParentDepartmentName; /
if (lstDepartmentDetails.Any(item => item.Name.CompareString(rootDepartmentName) && item.ParentName.IsNullOrEmpty()))
{
    clsRelFilter rootDepartment = lstDepartmentDetails.FirstOrDefault(item => item.Name.CompareString(rootDepartmentName) && item.ParentName.IsNullOrEmpty());
    TreeNode ParentNode = new TreeNode(rootDepartment.Name, rootDepartment.Uri);

    AddChildDepartmentsToNode(ParentNode, rootDepartment, lstDepartmentDetails);
    tvDepartments.Nodes.Add(ParentNode);
}

It's a classical problem in any tree based control. You could use some form of recursion such that at every parent checkbox selection, you go recursively through all of the children of that node (down to leaf level) and mark their checkboxes as selected as well. You can go depth first, until you have no more descendants, then climb back to the parent and so on.

Also, you should think about the ancestors as well. What if all children of a node are unchecked, should you uncheck the parent as well? Or, if you check a descendant, should you go up the tree and check the ancestor nodes as well?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM