How to bind TreeView and get selected node value in Asp.Net.


Aspx Page code for TreeView

<asp:TreeView ID="TreeMenu" runat="server" NodeWrap="true" ShowLines="true" ShowCheckBoxes="All">
    <DataBindings>
        <asp:TreeNodeBinding DataMember="System.Data.DataRowView"
            TextField="sMenuName" ValueField="iMenuId" />
    </DataBindings>
</asp:TreeView>

Data bind to TreeView

DataSet ds = //Dataset with child parent relationship;
TreeMenu.DataSource = new HierarchicalDataSet(ds, "iMenuId", "iParentId");
TreeMenu.DataBind();
TreeMenu.CollapseAll();
TreeMenu.Nodes[0].Expand();

Get the selected node value

if (TreeMenu.CheckedNodes.Count > 0)
{
    foreach (TreeNode node in TreeMenu.CheckedNodes)
    {
        checkedValue = node.Value;
        break;
    }
}

Allow only one checkbox checked at a time. Call javascript function

private void Page_PreRender(object sender, EventArgs e)
   {
       TreeMenu.Attributes.Add("OnClick", "client_OnTreeNodeChecked(event)");
   }

Javascript function

<script type="text/javascript">

function client_OnTreeNodeChecked(event) {
    var TreeNode = event.srcElement || event.target;
    if (TreeNode.tagName == "INPUT" && TreeNode.type == "checkbox") {
        if (TreeNode.checked) {
            uncheckOthers(TreeNode.id);
        }
    }
}

function uncheckOthers(id) {
    var elements = document.getElementsByTagName('input');
    // loop through all input elements in form
    for (var i = 0; i < elements.length; i++) {
        if (elements.item(i).type == "checkbox") {
            if (elements.item(i).id != id) {
                elements.item(i).checked = false;
            }
        }
    }
}
</script>