Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use Control.FindControl on dynamically created System.Web.UI.WebControl

Tags:

.net

asp.net

Why would the following code not work? I am creating a control, adding a child control and attempting to retrieve it by id using the .FindControl method.

[Test]
    public void TryToFindControl()
    {
        var myPanel = new Panel();
        var textField = new TextBox
        {
            ID = "mycontrol"
        };
        myPanel.Controls.Add(textField);

        var foundControl = myPanel.FindControl("mycontrol");

        // this fails
        Assert.IsNotNull(foundControl);
    }
like image 778
ktam33 Avatar asked Oct 01 '22 08:10

ktam33


2 Answers

Panel has not been added to Page yet, so you cannot use FindControl. Instead, you need to find it inside Panel.Controls

[TestMethod]
public void TryToFindControl()
{
    var myPanel = new Panel();
    var textField = new TextBox
    {
        ID = "mycontrol"
    };
    myPanel.Controls.Add(textField);

    var foundControl = myPanel.Controls
        .OfType<TextBox>()
        .FirstOrDefault(x => x.ID == "mycontrol");

    Assert.IsNotNull(foundControl);
}

Testing with Page

FindControl works only if container is added to Page.

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var myPanel = new Panel();
        var textField = new TextBox
        {
            ID = "mycontrol"
        };
        myPanel.Controls.Add(textField);

        Controls.Add(myPanel);

        // foundControl is not null anymore!
        var foundControl = myPanel.FindControl("mycontrol");
    }
}
like image 130
Win Avatar answered Oct 02 '22 22:10

Win


The control must be part of the server side Page control collection hierarchy to be found.

public void TryToFindControl()
{
    var myPanel = new Panel();

    // key line here
    Page.Controls.Add(myPanel); 

    var textField = new TextBox
    {
        ID = "mycontrol"
    };

    myPanel.Controls.Add(textField);

    var foundControl = myPanel.FindControl("mycontrol");

    Assert.IsNotNull(foundControl);
}
like image 37
andleer Avatar answered Oct 02 '22 20:10

andleer