繁体   English   中英

等效于ASP.NET Web窗体中的jQuery最近的()

[英]Equivalent to jQuery closest() in ASP.NET Web Forms

我试图找出一种在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或类型最接近的元素

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

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

谢谢!

也许像这样

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM