Thursday, July 3, 2008

Creating dynamic Controls on Web Page

Hi Friends, this is my first blog on "Dotnet Made easy" ever since I created this Blog. However, I have too many of the blogs saved as a draft copy :-)

This blog will take you through the process of creating dynamic controls (in this example we have created a Textbox and Button Control) and associating events with them.

Note -This blog assumes that the reader has knowledge of web applications.

The steps for Dynamically creating controls are as follows :-

1) Create a blank Web page in the Solution Explorer.

2) Drag a Table Control from the Toolbox on the screen. Table Control is present in the Standard tab of the toolbox.

3) Open the .aspx.cs / .aspx.vb codebehind file of the web page. We will go for .cs file i.e. C# code.

4) Start with the Page_Load Event

System.Web.UI.WebControls.TextBox txtbox = new System.Web.UI.WebControls.TextBox();

The above line initializes the TextBox Control, whose ID is given as txtbox. We can change the ID of the control by setting its property ID, e.g. txtbox.ID = "txtBox1";. We will not do and carry on with the ID given in the initialization statement.

5) We than create a row of the table and a cell for the row.

TableRow tblRow = new TableRow();
TableCell tblcell = new TableCell();

6) Next, we got to add the Control (txtbox) just intialized to the cell so that it becomes visible on the screen.

7) Next step is to add the cell to the row.

tblRow.Cells.Add(tblcell);

8) And finally we have to add the row that is created to the table.

Table1.Rows.Add(tblRow);

So the above steps are important in the creation of dynamic controls. It is not necessary that we can add the controls to the Table only, we can also add the controls to the Form. The syntax is simple - form.Controls.Add(txtbox);

Now we can also create a button control, the steps remain the same only that here we use the Button class.
Check the below code

TableCell tblcell2 = new TableCell();
System.Web.UI.WebControls.Button btn = new Button();
btn.Width = Unit.Pixel(100);
btn.Text = "Click Me";

tblcell2.Controls.Add(btn);

tblRow.Cells.Add(tblcell2);

Now that we know how to create a control, lets try adding Events to these control.

A button has a click event, so now we will create a click event of the Button and register it to the dynamic button we just created.

The syntax to register an event to a control is
btn.Click += new EventHandler(this.btn_Click);

Note that here += is used to assign the event. EventHandler is a delegate.

The way we write the Event function is the same as the one which is generated by .Net framework when we double click on button.

public void btn_Click(object o, EventArgs e)
{
//Your Code
Response.Write("Hello World");
}

I hope this article is useful to you.

Enjoy coding!!


2 comments:

Abhi said...

Hey, nice article. Very useful information.

Punam said...

thanks Sir.