代码之家  ›  专栏  ›  技术社区  ›  md1337

查找上一个和下一个同级控件

  •  5
  • md1337  · 技术社区  · 14 年前

    有没有一种方法可以在ASP.net窗体,类似于findControl()?

    如果您编写一个通用函数来处理几个布局相似的控件,并且不想逐个处理它们,那么这也很有用。

    谢谢你的建议。

    2 回复  |  直到 14 年前
        1
  •  7
  •   md1337    14 年前

    对于后人来说,这是我最后写的函数。效果非常好(在实际项目中进行了测试):

        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生成几个文本控件,以便在“真实”控件之间呈现静态HTML。这就是我跳过它们的原因,否则你会继续匹配垃圾。当然,这样做的缺点是如果它是一个文本,就找不到控件。这个限制在我的使用中不是问题。

        2
  •  1
  •   Atzoya    14 年前

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

    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();