Monday, February 05, 2007

Adding a WebControl before or after another one (ASP.NET C#)

ASP.NET does not directly allow you to add a WebControl after another one (i.e. you can't do MyRepeater.AddAfter(MyLiteral) to add MyLiteral after MyRepeater. These two simple functions allow you to do just that:

public void AddControlBefore(Control beforeControl, Control controlToAdd)
{
 Control container = beforeControl.NamingContainer as Control;
 container.Controls.AddAt(container.Controls.IndexOf(beforeControl), controlToAdd);
}
  
public void AddControlAfter(Control afterControl, Control controlToAdd)
{
 Control container = afterControl.NamingContainer as Control;
 container.Controls.AddAt(container.Controls.IndexOf(afterControl) + 1, controlToAdd);
}

No comments: