How to set focus to a web control in ASP.NET
Question: What is the best way to set focus to a web control in ASP .NET.
I can do it, but it's ugly. I have a web control wrapped in a web control hosted on a web page. So, if you do a view | source on the page the id is something like WrapperControl_Control_TextBox.
I've tried the "tried and true" Javascript methods of grabbing the element and setting it's focus: document.getElementByID( "WrapperControl_Control_TextBox" ).focus(); and it didn't work. I'm not sure why.
I know I could possibly do: document.getElementById( "<%= TextBox.ClientID %>" ).focus(); too, I think. This won't work because of another totally separate error based on the fact you can't dynamically add controls to a header if there is a "<% %>" in the page. GAH.
In the "bottom-most" control, I've tried setting the focus (TextBox.Focus() in Page_Load) and that doesn't work either.
Anyway, the way that works is by simply taking the ControlsCollection of the Page, grabbing the control I need from that, getting it's collection, grabbing the next lower control and so forth.
I only have to do this seven times. So I have eight foreach loops.
Basically, my code is like this:
/////////////////////////////// // On the page ///////////////////////////////
ControlCollection controls = Controls;
foreach( Control control in controls)
{
if ( string.Equals( control.ID, "FormID", StringComparison.InvariantCultureIgnore ) )
{
ControlCollection nextControls = control.Controls;
foreach( Control nextControl in nextControls )
{
if ( string.Equals( next开发者_StackOverflowControl.ID, "DivICareAboutInTheForm", StringComparison.InvariantCultureIgnor ) )
{
ControlCollection nextNextControls = nextControl.Controls;
//:
//:
//Yes, it's that bad and so forth.
//:
//:
}
}
}
}
You can use jQuery to do a search for IDs that end with your textbox name. This way you wont have to call the UniqueID server-side code. Just make sure not to have multiple controls that end with the same name
<script type="text/javascript">
$(document).ready(function() {
$('[id$=txtBox]').focus();
});
</script>
Or, you can use a Class name for the default text box.
<asp:Textbox ID="txtBox" runat="server" cCssClass="defaultTextbox" />
jquery:
$('.defaultTextbox').focus();
You can get around the "cannot add dynamic controls because a <%= %> block exists on the page" error by changing the block to use databinding syntax: <%# TextBox.ClientID %>
, and manually calling Page.DataBind()
in Page_Load.
If you really want to use the Page_Load
method, then you could always call the SetFocus method on the Page object.
Page.SetFocus(myTextBox);
精彩评论