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