About web form textbox focus question !!

  • Thread starter Thread starter Paul Tsai
  • Start date Start date
P

Paul Tsai

Dear All,

I used csharp web form to develop my company web application, and my
question is how shuld I do if I want to focus on my textbox(ex. like Java
Script form.txtID.focus()).

Thanks !!

Sincerely yous,
Paul
 
You'll have to use javascript code for setting focus. This can be done in the
codebehind file as follows:
(1) Write a method, say, SetFocus(Control x), which will register a
javascript code block.
(2) Call the SetFocus method with a control parameter from another method,
or event handler, say, Page_Load or Button1_click
(3) For detailed articles, follow this link
http://www.aspnetworld.com/articles/2004030301.aspx

The sample code is as follows:
private void SetFocus(Control x)
{
string clientId = x.ClientID;
StringBuilder strScript = new StringBuilder("<script
language='javascript'>\n");
strScript.Append("document.getElementById('" + clientId +
"').focus();\n");
strScript.Append("</script>\n");
Page.RegisterStartupScript("Focus",strScript.ToString());
}

private void Button1_Click(object sender, System.EventArgs e)
{
SetFocus(TextBox2);
}

Hope this helps.
 
Back
Top