Finding the previous and next sibling controls

前端 未结 2 1288

Is there a way to find the previous and next sibling controls in an ASP.net form from code-behind, similar to findControl()?

Sometimes you don\'t want to assign an I

2条回答
  •  执笔经年
    2021-01-13 13:08

    I don't think there is a built in function like that, but it is very easy to extend the Control class and add methods to it like so:

    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];
    }
    

    Of course a bit more handling needs to be done here (if there is no previous control or other scenarios) but i think you get the picture of how this could be done.

    After writing this method you can call it like

    Control textBox1 = textBox2.PreviousControl();
    

提交回复
热议问题