【问题标题】:How to find index of a control in a placeholder如何在占位符中查找控件的索引
【发布时间】:2014-02-20 22:22:37
【问题描述】:

我有以下代码:

   Label docsLabel = new Label();
   docsLabel = (Label)tasksPlaceholder.FindControl("taskdocs_" + taskId);
   int index = tasksPlaceholder.Controls.IndexOf(docsLabel);

标签位于占位符中,但当我调用 .IndexOf() 时,它总是返回 -1。

如何找到这个控件的正确位置?

【问题讨论】:

  • 当你在一行之后使用FindControl 时,你为什么还要使用new Label()?这只是令人困惑,什么也没做。
  • 可能是因为标签不是占位符的直接子代。
  • (Label)tasksPlaceholder.FindControl("taskdocs_" + taskId); 真的找到控件了吗?你不把null传给IndexOf()吗?
  • 它确实找到了控件,但它不是占位符的直接子元素。
  • @AndreJ,那么你不能指望它出现在占位符的控件集合中。

标签: c# asp.net indexof asp.net-placeholder


【解决方案1】:

这是您的 cmets 中的重要信息:

我要更新的元素向下 3 层(TableRow -> TableCell ->Label)

Control.FindControl 在此NamingContainer 中查找所有控件,而ControlCollection.IndexOf 仅在此控件中查找控件。因此,如果此控件包含例如包含行和单元格的表格,并且每个单元格还包含控件,则IndexOf 将不会找到所有这些控件,只会搜索顶部控件。

Control.FindControl 将搜索属于此NamingContainer(实现INamingContainer 的控件)的所有控件。表格/行/单元格没有实现它,这就是为什么所有这些控件也用FindControl搜索。

但是,FindControl 不会搜索子NamingContainers(就像GridViewRow 中的GridView)。

这重现了您的问题:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 2013-01-09
    相关资源
    最近更新 更多