How to set focus to a MS ASP.NET TreeView on form load






4.40/5 (12 votes)
Sep 10, 2003
2 min read

163286
This article will provide some tips on setting focus to a TreeView control.
Introduction
People have been having problems using the TreeView
control from Microsoft, for ASP.NET:
Microsoft.Web.UI.WebControls.TreeView
This control can be download for free from the Microsoft website. This page contains an overview of the free web controls (not supported by MS).
We will cover the focus issues for this control in this article. The reason I chose to create this article is that there was not much information after searching multiple sites. Basically this article will explain the two main problems: trying to get a TreeView
control to have focus and setting the colors properly, for hover and selected items.
Main information
Here is a list of problems trying to set focus to the Microsoft ASP.NET TreeView
control:
- Even though you place the
TreeView
inside a form, you have to use thedocument
object instead of theform
object to set the focus. Here is the final code:Private Sub focusTreeview() Dim strBuilder As StringBuilder = New StringBuilder() strBuilder.Append("<script language='javascript'>") strBuilder.Append("document.getElementById('TreeView1').focus();") 'Following line does nothing 'strBuilder.Append("document.getElementById('TreeView1').select();") strBuilder.Append("</script>") RegisterStartupScript("FocusTreeview", strBuilder.ToString) End Sub
After you use the code above, the
TreeView
will be selected on form load and user can properly select any item from theTreeView
. - Once you use the document's focus method, the colors stay in "light" mode no matter what you do, but, the
TreeView
is actually selected correctly. - The "select" statement does not have any effect on the
TreeView
. So if you un-comment the line above, it will have no effect on theTreeView
. - The way to make the colors not be in "light" mode is by using the filter style attribute in the
SelectedStyle
andHoverStyle
as follows:<iewc:treeview id="TreeView1" runat="server" DefaultStyle="font-family:arial;font-size:8pt;" SelectedStyle="filter=none;background-color:orange; font-weight:bold;" HoverStyle="filter=none;background-color:green;"> </iewc:treeview>
Notes
- The
filter=none
has to go before the other style keywords, if not you will just get a grey color. - Be sure to add
Imports System.Text
to the top of your code in order to use theStringBuilder
object. - The features described in this article only apply to MS Internet Explorer 6.x.