脚本|页面
Set the InitialFocus for an ASP.NET WebForm
The PageUtil class has a static method SetInitialFocus(control) which can be used to generate a JavaScript for an ASP.NET page (WebForm), which sets the focus on a (given) control.
private void Page_Load(object sender, System.EventArgs e)
{
// Set the InitialFocus on TextBox1
PageUtil.SetInitialFocus(TextBox1);
using System;
using System.Web.UI;
namespace InitialFocusDemo
{
/// <summary>
/// Utility class for a ASP.NET page
/// </summary>
public class PageUtil
{
/// <summary>
/// Set the IntialFocus to the given control. Only works when JavaScript is supported.
/// </summary>
/// <param name="control">Control to set the InitialFocus on.</param>
public static void SetInitialFocus(Control control) {
if (control.Page == null) {
throw new ArgumentException("The Control must be added to a Page before you can set the IntialFocus to it.");
}
if (control.Page.Request.Browser.JavaScript == true) {
control.Page.RegisterClientScriptBlock("InitialFocus",
"<SCRIPT FOR='window' EVENT='onload' LANGUAGE='JScript'>document.all."
+ control.UniqueID + ".focus();</SCRIPT>");
}
}
}
}