This is an important information in your comments:
the element I want to update is 3 levels down (TableRow -> TableCell ->Label)
Control.FindControl
finds all control in this NamingContainer
whereas ControlCollection.IndexOf
finds only controls in this control. So if this control contains for example a table which contains rows and cells and every cell contains also controls, all of these controls will not be found by IndexOf
, only the top-control is searched.
Control.FindControl
will search all controls that belong to this NamingContainer
(a control that implements INamingContainer
). A table/row/cell does not implement it, that's why all of these controls are also searched with FindControl
.
However, FindControl
will not search through sub-NamingContainers
(like a GridView
in a GridViewRow
).
This reproduces your issue:
protected void Page_Init(object sender, EventArgs e)
{
// TableRow -> TableCell ->Label
var table = new Table();
var row = new TableRow();
var cell = new TableCell();
var label = new Label();
label.ID = "taskdocs_1";
cell.Controls.Add(label);
row.Cells.Add(cell);
table.Rows.Add(row);
tasksPlaceholder.Controls.Add(table);
}
protected void Page_Load(object sender, EventArgs e)
{
Label docsLabel = (Label)tasksPlaceholder.FindControl("taskdocs_1");
int index = tasksPlaceholder.Controls.IndexOf(docsLabel);
// docsLabel != null and index = -1 --> quod erat demonstrandum
}
How do I find the correct position of this control?
If you want to find the row-number this label belongs to:
Label docsLabel = (Label)tasksPlaceholder.FindControl("taskdocs_1");
TableRow row = (TableRow)docsLabel.Parent;
Table table = (Table)row.Parent;
int rowNumber = table.Rows.GetRowIndex(row);