symbiont symbiont - 2 months ago 32
ASP.NET (C#) Question

TableRow.FindControl(cell.ID) returns null

why doesn't the cell i just added to a row get found with FindControl()?

// cell
var cell = new System.Web.UI.WebControls.TableCell();
cell.ID = "cell";

// cell in row
var row = new System.Web.UI.WebControls.TableRow();
row.Controls.Add(cell);

// get cell from row
var foundCell = row.FindControl(cell.ID);


foundCell becomes null

Answer

To FindControl a dynamic item that created from back-end programming code, asp.net need to post_back to add the Control to DOM.

In your case, you need to separate your Adding Control function and Finding Control function in different asp.net life-cycle.

First, Create the Control in Page_Init:

public void Page_Init(object sender, EventArgs e)
{
    // cell
    var cell = new System.Web.UI.WebControls.TableCell();
    cell.ID = "cell";

    // cell in row
    var row = new System.Web.UI.WebControls.TableRow();
    row.Controls.Add(cell);
}

Then you can find the Control in Page_Load:

protected void Page_Load(object sender, EventArgs e)
{
    // get cell from row
    var foundCell = Page.FindControl("cell"); // or you can store the cell Id in a string variable
}

You can find more info on MSDN, on the ASP.NET Page Life Cycle article.

Comments