【发布时间】:2011-10-02 19:19:48
【问题描述】:
我试图想办法在 C# 中构建一个有点聪明的 jQuery 最接近方法版本。我使用通用方法找到所需的控件,然后索引控件链
public static T FindControlRecursive<T>(Control control, string controlID, out List<Control> controlChain) where T : Control
{
controlChain = new List<Control>();
// Find the control.
if (control != null)
{
Control foundControl = control.FindControl(controlID);
if (foundControl != null)
{
// Add the control to the list
controlChain.Add(foundControl);
// Return the Control
return foundControl as T;
}
// Continue the search
foreach (Control c in control.Controls)
{
foundControl = FindControlRecursive<T>(c, controlID);
// Add the control to the list
controlChain.Add(foundControl);
if (foundControl != null)
{
// Return the Control
return foundControl as T;
}
}
}
return null;
}
叫它
List<Control> controlChain;
var myControl = FindControls.FindControlRecursive<TextBox>(form, "theTextboxId"), out controlChain);
寻找最接近id或type的元素
// Reverse the list so we search from the "myControl" and "up"
controlChain.Reverse();
// To find by id
var closestById = controlChain.Where(x => x.ID.Equals("desiredControlId")).FirstOrDefault();
// To find by type
var closestByType = controlChain.Where(x => x.GetType().Equals(typeof(RadioButton))).FirstOrDefault();
这是一个好方法还是有其他很酷的解决方案来创建它? 你有什么考虑?
谢谢!
【问题讨论】:
-
那么controlChain包含了指定ID控件的所有父控件?
-
是的,也许面包屑会是一个更好的名字。这只是关于如何构建这种方法的建议。也许它不是最好的模型?
-
我不确定问题是什么,除了“我做了这个,想法?”
-
那么……也许更适合CodeReview?
-
Sii,我想查看我的代码,但不知道 Joan 提到的网站。但是,我也很好奇是否有任何其他可用的解决方案可以执行该任务,所以无论如何这个问题并不完全符合 SO。
标签: c# asp.net webforms findcontrol