【问题标题】:Finding the previous and next sibling controls查找上一个和下一个同级控件
【发布时间】:2010-09-15 22:16:49
【问题描述】:

有没有办法从代码隐藏中找到 ASP.net 表单中的上一个和下一个同级控件,类似于 findControl()?

有时您不想将 ID 分配给控件,以便您可以执行 parent().findControl("ID") 来找到它。当我所能做的只是 previousControl() 或其他东西(如 jQuery)时,我已经厌倦了想出 ID。

这在您编写通用函数以处理具有相似布局但不想一个一个处理的多个控件的情况下也很有用。

感谢您的任何建议。

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    为了后代,这是我最终编写的函数。效果很好(在真实项目中测试):

        public static Control PreviousControl(this Control control)
        {
            ControlCollection siblings = control.Parent.Controls;
            for (int i = siblings.IndexOf(control) - 1; i >= 0; i--)
            {
                if (siblings[i].GetType() != typeof(LiteralControl) && siblings[i].GetType().BaseType != typeof(LiteralControl))
                {
                    return siblings[i];
                }
            }
            return null;
        }
    

    这样使用:

    Control panel = textBox.PreviousControl();
    

    对于下一个控制:

        public static Control NextControl(this Control control)
        {
            ControlCollection siblings = control.Parent.Controls;
            for (int i = siblings.IndexOf(control) + 1; i < siblings.Count; i++)
            {
                if (siblings[i].GetType() != typeof(LiteralControl) && siblings[i].GetType().BaseType != typeof(LiteralControl))
                {
                    return siblings[i];
                }
            }
            return null;
        }
    

    此解决方案相对于 Atzoya 解决方案的优势在于,首先,您不需要原始控件具有 ID,因为我基于实例进行搜索。其次,您必须知道 ASP.net 会生成多个 Literal 控件,以便在“真实”控件之间呈现静态 HTML。这就是我跳过它们的原因,否则你会继续匹配垃圾。当然,这样做的缺点是如果它是 Literal,您将找不到控件。这个限制在我的使用中不是问题。

    【讨论】:

      【解决方案2】:

      我不认为有这样的内置函数,但是像这样扩展 Control 类并为其添加方法非常容易:

      public static Control PreviousControl(this Control control)  
      {
         for(int i=0; i<= control.Parent.Controls.Count; i++)
            if(control.Parent.Controls[i].Id == control.Id)
               return control.Parent.Controls[i-1];
      }
      

      当然,这里需要做更多的处理(如果没有以前的控制或其他场景),但我想你已经了解了如何做到这一点。

      写完这个方法后就可以这样调用了

      Control textBox1 = textBox2.PreviousControl();
      

      【讨论】:

      • 感谢您的建议,但它有两个问题:首先您假设原始控件必须有一个ID,这在我的情况下不好。其次,您的函数将与 ASP.net 生成的文字控件相匹配,以便输出您的静态 HTML。那是不行的。请参阅我自己的解决方案,了解解决所有这些问题的版本。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      相关资源
      最近更新 更多