How to bring RadioButton instead of CheckBox in asp:TreeView control

Posted by in ASP.NET category on for Advance level | Points: 200 | Views : 14433 red flag
Rating: 5 out of 5  
 2 vote(s)

I had a scenario where I wanted to convert the CheckBoxes of the TreeView to radio buttons and user should be able to select only one radiobutton items for a single parent node. I googled and couldn't find an easy way to do that and after that I came to this code snippet and it really works great.

This article explain u how you can add the radio button in instead of checkbox in TreeView.


This article explains, how one can add the radio button instead of checkbox in TreeView ASP.NET server control. It can be used in the scenario where you wants’ your user to select only one item out of group of items.

Using the code

Below is the code for the TreeView control and the code behind.

Treeview Code in ASP.NET page

 <asp:TreeView runat="server" ID="tvAi" Font-Bold="true" ShowLines="true" EnableClientScript="true"
                ShowExpandCollapse="true" ShowCheckBoxes="All"  
                SelectedNodeStyle-ForeColor="Azure" >
DataBind Code at server side
 private void BindTreeview()
            var pk = this.GetTreeViewNodes(); // this is simply to get the records to bind into the GridView           
            int redindex = 1;
             foreach (var parentNode in pk)
                TreeNode master = new TreeNode(parentNode.Value.ToString(), parentNode.Key.ToString());
                master.ShowCheckBox = false;

                var sk = this.GetSubnodesOfTheParentNodes(parentNode.Key);

                foreach (var chileNode in sk)
                     TreeNode child = new TreeNode(chileNode.Value.ToString(), chileNode.Key.ToString());
                     child.ShowCheckBox = false;
                     child.Text = "<input type='radio' name='rdoC" + redindex.ToString() + "' value ='"+chileNode.Value.ToString()+"' />" + child.Text;

In the above code snippet, we have first retrieved the parent nodes record from  the database and added into the TreeView and then retrieved the child nodes from the TreeView and added against each parent node. Instead of showing CheckBoxes (note that we have set ShowCheckBox to false), we have set the text of the node to the radio button code. Here as the name of the children radio buttons will be similar for a parent node so user will be able to select only radio button item for a single parent.

Interesting !!!!


Using the above code now you can convert the checkboxes to radiobuttons. Hope this unique code snippet will help you.
Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: vishal bedre
Member Level: Starter
Member Status: Member
Member Since: 9/1/2011 5:06:08 PM
Country: United States

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)