Data Cogs Information Technology

posts - 137, comments - 144, trackbacks - 42

General

Search This Site

Powered by Google

Brisbane

Locations of visitors to this page

Archives

Did you ever have the need to conditionally set focus to a control in a WebForm or UserControl from server side code?  This bit of code will add an “onload“ attribute to the body tag (even from a UserControl). You need to make sure the body tag is runat=“server“ and that you give it an ID.  Then use Page.FindControl to locate the body tag and set the focus to any control.  Use the control's ClientID property to make sure you get the correct client-side id.

private void Button1_Click(object sender, System.EventArgs e)
{
 HtmlContainerControl body = (HtmlContainerControl) Page.FindControl("bdBody");
 body.Attributes.Add("onload", "document.all." + this.TextBox1.ClientID + ".focus();");
}

Another way to accomplish the same thing is with Page.RegisterStartupScript...

public void SetFocus( TextBox tb ) 
{
   this.Page.RegisterStartupScript("SetFocus","<script>document.forms[0]." + tb.ClientID + ".focus();</script>"); 
}

posted on Friday, October 15, 2004 9:41 AM

Feedback

# re: Getting at the Body tag from a UserControl

this is a very helpful peice of code, great stuff.
10/15/2004 9:33 PM | clayton

Post Comment

Title  
Name  
Url
Comment   
Protected by Clearscreen.SharpHIPEnter the code you see: