找到上一个和下一个兄弟控件

问题描述:

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

有时你不想为控件分配一个ID,所以你可以做一个父()。findControl(“ID”)以便找到它。当我所能做的就是previousControl()或者其他的东西(la jQuery)时,我厌倦了提供ID。

这对于编写一个通用函数以解决具有相似布局且不想逐一解决它们的多个控件的情况也很有用。

感谢您的任何建议。

对于后人,这里是我结束了写作的功能。工作得非常好(在实际项目中进行测试):

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。这就是为什么我跳过他们,否则你会保持匹配的垃圾。当然,这个缺点是如果它是一个文字,你无法找到一个控件。这个限制在我的使用中不是问题。

我不认为这是一个建在这样的功能,但它是非常容易扩展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(); 
+3

谢谢你的建议,但它有两个问题:首先你认为原始控件必须有一个ID,这在我的情况下不好。其次,您的函数将与ASP.net生成的Literal控件匹配,以输出静态HTML。这是不行的。查看我自己的解决方案,获取解决所有问题的版本。 – md1337 2010-09-15 14:20:19