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

md1*_*337 5 asp.net

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

有时您不想为控件分配ID,因此您可以执行parent().findControl("ID")以便找到它.当我所能做的就是previousControl()或其他东西(la jQuery)时,我已经厌倦了提出ID.

这对于编写常规函数以解决具有类似布局且不想逐个解决它们的多个控件的情况也很有用.

谢谢你的任何建议.

md1*_*337 7

对于后人来说,这是我最终写作的功能.效果很好(在实际项目中测试):

    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;
    }
Run Code Online (Sandbox Code Playgroud)

要像这样使用:

Control panel = textBox.PreviousControl();
Run Code Online (Sandbox Code Playgroud)

并为下一个控制:

    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;
    }
Run Code Online (Sandbox Code Playgroud)

这个解决方案优于Atzoya的优势在于,首先,您不需要原始控件来获取ID,因为我根据实例进行搜索.其次,您必须知道ASP.net会生成多个Literal控件,以便在您的"真实"控件之间呈现静态HTML.这就是我跳过它们的原因,或者你会继续匹配垃圾.当然,这样做的缺点是,如果它是一个文字,你就找不到控件.这个限制在我的使用中不是问题.