我試圖找出一種方法來構建一個在C#中的jQuery最接近的方法的一個稍微聰明的版本。即時通訊使用的通用方法,以找到所希望的控制,然後索引的控制鏈相當於jQuery最接近()在ASP.NET Web窗體
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最接近元件或鍵入
// 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控制所有的家長? – Magnus
是的,也許麪包屑會是一個更好的名字。這只是建議如何建立這樣的方法。也許這不是最好的模式? –
我不確定問題是什麼,除了「我做了這個,想法?」 – millimoose