我使用以下方法递归地在asp.net页面上查找控件:
/// <summary>
/// Searches recursively for a server control with the specified id parameter.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="id">The id.</param>
/// <returns>A <see cref="Control"/></returns>
public static Control FindControl(Control start, string id)
{
Control foundControl;
if (start == null)
return null;
foundControl = start.FindControl(id);
if (foundControl != null)
return foundControl;
foreach (Control c in start.Controls)
{
foundControl = FindControl(c, id);
if (foundControl != null)
return foundControl;
}
return null;
}
我遇到了问题,因为它返回了错误的控件。我将问题跟踪到标准FindControl方法,并通过检查返回的控件的ID确实与请求的ID匹配来修复它:
foundControl = start.FindControl(id);
if (foundControl != null && foundControl.ID == id)
return foundControl;
我的问题是为什么start.FindControl(id)会返回一个与所请求的id不匹配的控件?
答案 0 :(得分:2)
我用
static class ControlExtension
{
public static IEnumerable<Control> GetAllControls(this Control parent)
{
foreach (Control control in parent.Controls)
{
yield return control;
foreach (Control descendant in control.GetAllControls())
{
yield return descendant;
}
}
}
}
并致电
var foundControl = Page.GetAllControls().Where(c => c.ID = id);
编辑:
也许不是叫它开始搜索
foundControl = start.FindControl(id);
你应该从
开始foundControl = FindControl(start, id);