0

I'm trying to generate dynamic nested CheckBoxLists in .NET using C#.

I want to display departments and areas with a checkbox next to each. When the checkbox is checked for a department, it should then display the areas for that department right below it, indented, with checkboxes next to them.

I'm able to generate the departments with checkboxes dynamically, but I'm not sure how to go about doing the areas. Part of the issue is that I don't have individual IDs for each department, it's just a list.

<div class="TABLE">
    <div class="ROW">
        <div class="CELL CELL50">
            <asp:CheckBoxList id="cblDepts" runat="server" OnSelectedIndexChange="cblDepts_OnSelectedIndexChange"></asp:CheckBoxList>
        </div>
        <div class="CELL CELL50">
            <asp:CheckBoxList id="cblAreas" runat="server" Visible="false"> 
         </asp:CheckBoxList>
        </div>
    </div>
</div>

protected void LoadFilters()
    {
        _datalayer = new DataLayer();
        deptAreas = new Dictionary<string, Tuple<string, string>>();
        Dictionary<string, string> depts = new Dictionary<string, string>();
        DataSet dsDepts = _datalayer.GetDepartments();

        if(dsDepts != null && dsDepts.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dr in dsDepts.Tables[0].Rows)
            {
                depts.Add(dr["DepartmentId"].ToString(), dr["DepartmentDetails"].ToString());
            }
        }

        this.cblDepts.Items.Clear();
        this.cblAreas.Items.Clear();

        foreach(var dept in depts)
        {
            this.cblDepts.Items.Add(new ListItem(dept.Value, dept.Key));
            DataSet dsAreas = _datalayer.GetAreas(dept.Key.ToChange<int>().Value);

            if(dsAreas != null && dsAreas.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in dsAreas.Tables[0].Rows)
                {
                    deptAreas.Add(dept.Key, Tuple.Create(dr["AreaId"].ToString(), dr["AreaDetails"].ToString()));
                }
            }

        }

    }

The result should be that when you click the checkbox next to a department, the areas for that department are displayed below that department, indented, with a checkbox next to each.

3 Answers 3

0

A super simplistic example is the following:

<div class="TABLE">
        <div class="ROW">
            <div class="CELL CELL50">
                <asp:CheckBoxList ID="cblDepts" runat="server" OnSelectedIndexChanged="cblDepts_SelectedIndexChanged" AutoPostBack="True"></asp:CheckBoxList>
            </div>
            <div class="CELL CELL50">
                <asp:CheckBoxList ID="cblAreas" runat="server" Visible="false">
                </asp:CheckBoxList>
            </div>
        </div>
    </div>

public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.cblDepts.Items.Add(new ListItem() { Text = "1", Value = "1" });
                this.cblDepts.Items.Add(new ListItem() { Text = "2", Value = "2" });
                this.cblDepts.Items.Add(new ListItem() { Text = "3", Value = "3" });
            }
        }

        protected void cblDepts_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.cblAreas.Items.Clear();
            foreach (ListItem item in this.cblDepts.Items) {
                var selectedValue = "-1";
                if (item.Selected)
                {
                    selectedValue = item.Value;
                }

                if (selectedValue == "1")
                {
                    this.cblAreas.Items.Add(new ListItem() { Text = "1.1", Value = "1.1" });
                }
                else if (selectedValue == "2")
                {
                    this.cblAreas.Items.Add(new ListItem() { Text = "2.2", Value = "2.2" });
                }
                else if (selectedValue == "3")
                {
                    this.cblAreas.Items.Add(new ListItem() { Text = "3.3", Value = "3.3" });
                }
            }

            if (this.cblAreas.Items == null || this.cblAreas.Items.Count == 0)
            {
                this.cblAreas.Visible = false;
            }
            else
            {
                this.cblAreas.Visible = true;
            }

        }
    }

Above example is dummy and for demonstration only, it is in no way proper code for production but you get the idea! <3

Sign up to request clarification or add additional context in comments.

2 Comments

This is helpful and gets me part of the way there. I need the values to appear below the department though. So, for example, you could have departments Accounting then HR--then HR has items below it, indented--then back in the departments list would be Operations, etc. I think the solution is mainly HTML and some .NET data binding.
Here in Greece it is 00:00 midnight, i can come back tomorrow morning and help 😜👊🏼
0

If using javascript is not an issue for you, you can do the following:

<asp:Repeater ID="DepartmentsRepeater" runat="server">
        <ItemTemplate>
            <input class="departments" onclick="show(this)" type="checkbox" value="<%# Container.DataItem?.ToString() %>" /><%# Container.DataItem?.ToString() %> </br>
            <asp:Repeater ID="AreasRepeater" runat="server" DataSource='<%# GetAreasOfDepartment(Container.DataItem?.ToString()) %>'>
                <ItemTemplate>
                    <div class="areas <%#((RepeaterItem)Container.Parent.Parent).DataItem?.ToString() %>">
                        <input type="checkbox" value="<%# Container.DataItem?.ToString() %>" /><%# Container.DataItem?.ToString() %> </br>
                    </div>
                </ItemTemplate>
            </asp:Repeater>
        </ItemTemplate>
    </asp:Repeater>

    <script>
        $(".areas").hide();

        function show(e) {
            $(".areas").hide();
            $(".departments").each(function (d) {
                if (this.checked) {
                    var c = "." + this.value;
                    $(c).show();
                }
            })
        }
    </script>


public partial class _Default : Page
    {
        public List<string> Departments = new List<string> { "HR", "Finance" };
        public Dictionary<string, List<string>> Areas = new Dictionary<string, List<string>>
        {
            {"HR", new List<string>{"HR1","HR2"} },
            {"Finance", new List<string>{ "Finance1", "Finance2" } }
        };
        protected void Page_Load(object sender, EventArgs e)
        {
            this.DepartmentsRepeater.DataSource = Departments;
            this.DepartmentsRepeater.DataBind();
        }

        public List<string> GetAreasOfDepartment(string dep)
        {
            return Areas[dep];
        }
    }

As previously stated, this code is for demonstration only and not optimized for production use <3

1 Comment

Thanks for your help, Ricky. I tried this code but there seems to be a problem with the HTML and JavaScript/jQuery. For the error it says: "CS1525 Invalid expression term '.' and it doesn't like this line: <input class="departments" onclick="show(this)" type="checkbox" value="<%# Container.DataItem?.ToString() %>" /><%# Container.DataItem?.ToString() %> </br>
0

Writing all the code is really hard without doing it in Visual Studio. So here I will help you get started. As I understand that each department have a list of area, you should create a class that tells that.

Like this for example:

public class Area()
public int AreaId {get; set; }

public string AreaDetails { get; set; }

}

public class Departments (){
public int DepartmentId { get; set; }

public string DepartmentDetails { get; set; }

public List<Area> Areas { get; set; } // all area that are included in the current depertment

}

When you have the list you should now start be creating the checkboxes.

So you can now retrieve the department id that you want OnSelectedIndexChange. Next you find the selected department in the List and then create the checkboxes and a div detail department and Areas.

You know how to create checkbox list but here is a link if you need more information: How to create dynamic checkbox in asp.net

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.