相当于ASP.NET Web窗体中的jQuery nearest()

时间:2011-10-02 19:19:48

标签: c# asp.net webforms findcontrol

我试图想出一种方法来在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();

这会是一个好方法还是还有其他很酷的解决方案吗? 您的考虑是什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

也许是这样的

public static IEnumerable<Control> GetControlHierarchy(Control parent, string controlID)
{
    foreach (Control ctrl in parent.Controls)
    {
        if (ctrl.ID == controlID)
            yield return ctrl;
        else
        {
            var result = GetControlHierarchy(ctrl, controlID);
            if (result != null)
                yield return ctrl;
        }
        yield return null;
    }
}