Introduction
This article helps you to have radio buttons or option buttons with tree view. Normally treeview controls with ASP.NET allows to have checkboxes. By using a simple
JavaScript it is possible to convert check boxes to radio buttons. Also, another small
JavaScript allows only one node be selected at a time. While selecting a node it will
uncheck/unselect all other nodes.
Using the code
Tree View in source
<asp:TreeView ID="TreeView1" runat="server"
ShowLines="True" ShowCheckBoxes="All">
<Nodes>
<asp:TreeNode Text="Root" Value="Root">
<asp:TreeNode Text="Parent 1" Value="New Node">
<asp:TreeNode Text="Leaf 1" Value="New Node"></asp:TreeNode>
<asp:TreeNode Text="Leaf 2" Value="New Node"></asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="Parent 2" Value="New Node">
<asp:TreeNode Text="Leaf 3" Value="New Node"></asp:TreeNode>
<asp:TreeNode Text="Leaf 4" Value="New Node"></asp:TreeNode>
</asp:TreeNode>
</asp:TreeNode>
</Nodes>
</asp:TreeView>
JavaScript to convert checkboxes to Radio Buttons
<script type="text/javascript">
function MakeRadio() {
var tv = document.getElementById("<%= TreeView1.ClientID %>");
var chkArray = tv.getElementsByTagName("input");
for (i = 0; i <= chkArray.length - 1; i++) {
if (chkArray[i].type == 'checkbox') {
chkArray[i].type = 'radio';
}
}
}
window.onload = MakeRadio;
</script>
JavaScript to convert Select single Radio Button at a time
<script type="text/javascript">
function OnTreeClick(evt) {
var src = window.event != window.undefined ? window.event.srcElement : evt.target;
var isChkBoxClick = (src.tagName.toLowerCase() == "input" && src.type == "radio");
if (isChkBoxClick) {
SelectOne(src.id);
}
}
function SelectOne(objId) {
var tv = document.getElementById("<%= TreeView1.ClientID %>");
var chkArray = tv.getElementsByTagName("input");
for (i = 0; i <= chkArray.length - 1; i++) {
if (chkArray[i].type == 'radio') {
if (chkArray[i].id != objId) {
chkArray[i].checked = false;
}
}
}
}
</script>
In code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TreeView1.Attributes.Add("onclick", "OnTreeClick(event)");
}
}