Search code examples
c#asp.netmaster-pageswebformsclientscript

Setfocus() in master page


I have the set focus for a property which I am trying to use in the masterpage but I am unable to do so.

public partial class Site1 : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
            Page.MaintainScrollPositionOnPostBack = true;
            SetFocus(this);

    }
      public void SetFocus(Site1 site1)
    {
        string[] sCtrl = null;
        string sCtrlId = null;
        Control sCtrlFound = default(Control);
        string sCtrlClientId = null;
        string sScript = null;

        sCtrl = site1.Request.Form.GetValues("__EVENTTARGET");
        if ((sCtrl != null))
        {
            sCtrlId = sCtrl[0];
            sCtrlFound = site1.FindControl(sCtrlId);
            Global.logger.Info("sCtrlId = " + sCtrlId + ", " + sCtrlFound);
            if ((sCtrlFound != null))
            {
                sCtrlClientId = sCtrlFound.ClientID;
                Global.logger.Info("sCtrlClientId = " + sCtrlClientId);

                sScript = "<SCRIPT language='javascript'>document.getElementById('" + sCtrlClientId + "').focus(); if (document.getElementById('" + sCtrlClientId + "').scrollIntoView(false)) {document.getElementById('" + sCtrlClientId + "').scrollIntoView(true)} </SCRIPT>";

                site1.ClientScript.RegisterStartupScript(typeof(string), "controlFocus", sScript);

            }
        }
    }
    }

I get an error on the last line:

'System.Web.UI.MasterPage' does not contain a definition for 'ClientScript' and no extension method 'ClientScript' accepting a first argument of type 'System.Web.UI.MasterPage' could be found (are you missing a using directive or an assembly reference?)

This code works fine on the normal content page. The error only happnes on the master page.

Do you have any suggestion for what I can do to make the above code work?


Solution

  • I'm not sure if this works but it should at least compile:

    Replace:

    site1.ClientScript.RegisterStartupScript(typeof(string), "controlFocus", sScript);
    

    With:

    site1.Page.ClientScript.RegisterStartupScript(GetType(String), "controlFocus", sScript);