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

本文关键字:NET Web 窗体 close ASP 中的 jQuery 相当于 | 更新日期: 2023-09-27 18:10:26

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

这是一个好方法吗?或者有其他很酷的解决方案吗?你的考虑是什么?

谢谢!

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

可能是这样的

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