2017年6月30日 星期五

【ASP.NET Webform】Recursive get specific type of control in container & filter id with string

遞回取得容器控制項中的指定型別子控制項集合與篩選 ID 包含特定字串

public static List<T> FindSpecTypeCtrls<T>(this Control container, List<T> ctrls) 
    where T : Control
{
    if (container.Controls.OfType<Control>().Any())
    {
        foreach (Control item in container.Controls.OfType<Control>())
        {
            if (item is T)
            {
                T obj = (T)item;
                ctrls.Add(obj);
            }
            else
            {
                FindSpecTypeCtrls<T>(item, ctrls);
            }
        }
    }

    return ctrls;
}

public static List<T> FindSpecTypeCtrlsWhereIdContainsStr<T>(this Control container, string str) 
    where T : Control
{            
    List<T> ctrls = new List<T>();
    FindSpecTypeCtrls<T>(container, ctrls);
    ctrls = ctrls.Where(ctrl => !string.IsNullOrEmpty(ctrl.ID) && ctrl.ID.Contains(str)).ToList();

    return ctrls;
}

使用 masterpage
public static ContentPlaceHolder GetPlaceHolderById(this Page page, string placeHolderId)
{
    return (ContentPlaceHolder)page.Master.FindControl(placeHolderId);
}

public static T FindCtrlByIdInMasterPage<T>(this Page page, string placeHolderId, string id)
    where T : Control
{
    T ctrl = (T)page.GetPlaceHolderById(placeHolderId).FindControl(id);

    return ctrl;
}

沒有留言:

張貼留言