簡體   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