Thursday, July 19, 2012

Programatically set the initial selected node in an ASP.NET TreeView control

I just ran into a scenario in which I wanted to have the first node in a TreeView control selected the first time the user accesses the given page (i.e. the node is set when the page was initially loaded).  In order to make this work properly, I had to add two lines of code to my PageLoad event that performed the following actions:
  1. Set the selected node of the TreeView control
  2. Trigger the Treeview.SelectedNodeChanged event to simulate the user clicking on the given node
Here is a summarized sample of the code that I added to my PageLoad event that allowed me to simulate a user clicking on the first node when the page was initially loaded:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // Code that initializes the TreeView
        ...

        treeViewControl.Nodes[0].Select();
        treeViewControl_SelectedNodeChanged(this, EventArgs.Empty);
    }
}
If you'd like to select a certain node, my thought is that you could use the TreeView.FindNode method to locate a particular node in the list. In that case, your code would appear as follows:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // Code that initializes the TreeView
        ...

        treeViewControl.FindNode(PathOfNode).Select();
        treeViewControl_SelectedNodeChanged(this, EventArgs.Empty);
    }
}
Naturally, you will need to write some additional code to look up the path to your given node, but my hope is that this will give you some idea as to how this might be accomplished.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.