Working with dynamic controls in ASP.NET is real pain for developer. First you have to create instance of control, then to configure all properties of control through code and then to look for any container control where you can drop this dynamic control. Interestingly, you also have to recreate same dynamic control on every PostBack.
Let’s start will simple example to work with dynamic control:
Label dynamicLabel = new Label();
dynamicLabel.ID = "dynamicLabel";
dynamicLabel.Width = Unit.Pixel(200);
dynamicLabel.Text = "Test Text";
Page.Controls.Add(dynamicLabel);
This code will simply add a dynamic label in Page.
But how we can position this control to specific location in the page? That should be easy, we can use Top & Left property of this control! But if you check the properties of Label, there is no Top or Left property available. So then how we can set its location?? Well, using style attribute of control. But for that you also have to set control position style as absolute. Like this:
Label dynamicLabel = new Label();
dynamicLabel.ID = "dynamicLabel";
dynamicLabel.Width = Unit.Pixel(200);
dynamicLabel.Style.Add("POSITION", "absolute");
dynamicLabel.Style.Add("TOP", "100px");
dynamicLabel.Style.Add("LEFT", "200px");
dynamicLabel.Text = "Test Text";
Page.Controls.Add(dynamicLabel);

Recent Comments