Can't use Control.FindControl on dynamically created System.Web.UI.WebControl
.net, asp.net
Solution
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");
}
}
Problem
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); } ```