[英]How to find index of a control in a placeholder
我有以下代碼:
Label docsLabel = new Label();
docsLabel = (Label)tasksPlaceholder.FindControl("taskdocs_" + taskId);
int index = tasksPlaceholder.Controls.IndexOf(docsLabel);
標簽位於占位符內,但是當我調用.IndexOf()時,它始終返回-1。
如何找到此控件的正確位置?
這是您評論中的重要信息:
我要更新的元素向下3級(TableRow-> TableCell-> Label)
Control.FindControl
在此NamingContainer
查找所有控件,而ControlCollection.IndexOf
僅在此控件中查找控件。 因此,如果此控件包含(例如)包含行和單元格的表,並且每個單元格還包含控件,則IndexOf
不會找到所有這些控件,而僅搜索頂部控件。
Control.FindControl
將搜索屬於此NamingContainer
所有控件(實現INamingContainer
)。 表/行/單元格沒有實現它,這就是為什么還使用FindControl
搜索所有這些控件的原因。
但是, FindControl
不會搜索子NamingContainers
(例如GridView
中的GridViewRow
)。
重現您的問題:
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
}
如何找到此控件的正確位置?
如果要查找該標簽所屬的行號:
Label docsLabel = (Label)tasksPlaceholder.FindControl("taskdocs_1");
TableRow row = (TableRow)docsLabel.Parent;
Table table = (Table)row.Parent;
int rowNumber = table.Rows.GetRowIndex(row);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.