Home > Net >  ASP.NET TreeView checkboxes behave as Radio Buttons
ASP.NET TreeView checkboxes behave as Radio Buttons

Time:10-09

I'm using a TreeView Control on ASP.NET with C#, and needs to make all the nodes (Roots and Leafs) with checkboxes. Then, I need these checkboxes to work as Radio Buttons so when clicking on one checkbox, the previously checked checkbox is now unchecked and the new one is becoming checked.

My work on this problem was first to add showCheckBoxes="All" attribute to the asp:TreeView then to use the TreeView1_TreeNodeCheckChanged event. However, this event is not triggered automatically and needs a postback for the page to fire up! So I used a javascript function to make it fire up as recommended on similar posts in stackoverflow.com but for different problems.

<script type="text/javascript">
    function postBackByObject() {
        var o = window.event.srcElement;
        if (o.tagName == "INPUT" && o.type == "checkbox") {
            __doPostBack("", "");
        }
    }
</script>


protected void Page_Load(object sender, EventArgs e)
        {
          TreeView1.Attributes.Add("onclick", "postBackByObject()");    
        }

However, still I couldn't figure out how to write the TreeNodeCheckChanged function to make the previously checked checkbox unchecked , and make the new one checked! As the post back action is making a confusion for me.

Thanks in Advance

CodePudding user response:

Hum, you could do this 100% client side.

We would on page load:

Select the treeview.

Then select any check boxes showing and add a click event.

And in that click event?

get the check box we cliked on - save setting.

Uncheck all check boxes.

Check/uncheck the one we clicked on back to its state.

This seems to work:

    <script>
        // select all check boxes - add event to that check box
        // on page load

        $(window).on('load', function () {
            tv = $('#TreeView1')
            nodes = tv.find('input[type=checkbox]')
            nodes.each(function () {
                $(this).change(function () { mycheck(this) } )
            })
        })

        function mycheck(e) {
            mychecked = e.checked    // save current check box
            myParent = $(e).closest('[id$=Nodes]')     // get current node
            clist = myParent.find('input[type=checkbox]')  // get all checkc box in node
            clist.each(function () {
                this.checked = false     // uncheck them all
            })
            e.checked = mychecked        // set state of the box we checked or un-checked.
        }
    </script>

So, I get/see this:

enter image description here

  • Related