How to make the Default focus in content page from master page

后端 未结 6 1847
我在风中等你
我在风中等你 2021-01-07 07:57

I have masterpage with content place holder. i have contentpage which is using master page . in all my content page i need to default focus on the text b

6条回答
  •  被撕碎了的回忆
    2021-01-07 08:18

    You could include this in your master page's load event:

    // if the ID is constant you can use this:
    /*TextBox textBox = (TextBox)Page.Controls[0]
                                    .FindControl("ContentPlaceHolder1")
                                    .FindControl("myTextBox");
    */
    
    // this will look for the 1st textbox without hardcoding the ID
    TextBox textBox = (TextBox)Page.Controls[0]
                                .FindControl("ContentPlaceHolder1")
                                .Controls.OfType()
                                .FirstOrDefault();
    
    if (textBox != null)
    {
        textBox.Focus();
    }
    

    This would match up with a content page that has the following markup:

    
        
    
    

    EDIT: if LINQ isn't an option then you can use this instead:

    foreach (Control control in Page.Controls[0].FindControl("ContentPlaceHolder1").Controls)
    {
        if (control is TextBox)
        {
            ((TextBox)control).Focus();
            break;
        }
    }
    

提交回复
热议问题