【问题标题】:Equivalent to jQuery closest() in ASP.NET Web Forms等效于 ASP.NET Web 窗体中的 jQuery 最接近()
【发布时间】:2011-10-02 19:19:48
【问题描述】:

我试图想办法在 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();

这是一个好方法还是有其他很酷的解决方案来创建它? 你有什么考虑?

谢谢!

【问题讨论】:

  • 那么controlChain包含了指定ID控件的所有父控件?
  • 是的,也许面包屑会是一个更好的名字。这只是关于如何构建这种方法的建议。也许它不是最好的模型?
  • 我不确定问题是什么,除了“我做了这个,想法?”
  • 那么……也许更适合CodeReview
  • Sii,我想查看我的代码,但不知道 Joan 提到的网站。但是,我也很好奇是否有任何其他可用的解决方案可以执行该任务,所以无论如何这个问题并不完全符合 SO。

标签: c# asp.net webforms findcontrol


【解决方案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;
    }
}

【讨论】:

  • 修复了脚本,现在可以编译了,这实际上是我今天的问题的解决方案。谢谢一百万!
  • 您好,我是 ASP.NET 新手,我正在尝试做同样的事情,您能解释一下这段代码是如何工作的吗?谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 2012-09-10
  • 1970-01-01
  • 2010-10-03
  • 2012-01-23
相关资源
最近更新 更多