Skip to main content

Practical-16

Problem Statement

Write a program using TreeView Control.

Solution

To create a program using TreeView Control in ASP.NET, follow the steps below:

  1. Create a new ASP.NET Web Application project in Visual Studio.
  2. Add a new Web Form to the project by right-clicking on the project in the Solution Explorer, selecting "Add" > "Web Form".
  3. Rename the Web Form to "Default.aspx".
  4. Open the "Default.aspx" file and design the user interface as per your requirements using HTML and ASP.NET controls.
  5. Add the following controls to the "Default.aspx" form:
    • TreeView control: <asp:TreeView ID="tvMenu" runat="server"></asp:TreeView>
  6. In the code-behind file, write the following code in the Page_Load event handler to populate the TreeView control:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TreeNode root = new TreeNode("Root");
tvMenu.Nodes.Add(root);

TreeNode node1 = new TreeNode("Node 1");
root.ChildNodes.Add(node1);

TreeNode node2 = new TreeNode("Node 2");
root.ChildNodes.Add(node2);

TreeNode node3 = new TreeNode("Node 3");
root.ChildNodes.Add(node3);

TreeNode subNode1 = new TreeNode("Sub Node 1");
node1.ChildNodes.Add(subNode1);

TreeNode subNode2 = new TreeNode("Sub Node 2");
node1.ChildNodes.Add(subNode2);

TreeNode subNode3 = new TreeNode("Sub Node 3");
node2.ChildNodes.Add(subNode3);
}
}
  1. Build and run the application to see the TreeView control in action.

This completes the solution for creating a program using TreeView Control in ASP.NET.