Click here to Skip to main content
15,860,943 members
Articles / Web Development / ASP.NET
Article

Dynamic creation of ASP.NET server controls on fly and doing validation by attaching Events in ASP.NET and C#.NET

Rate me:
Please Sign up or sign in to vote.
4.28/5 (22 votes)
14 Jun 20064 min read 143.1K   3.1K   49   12
Creation of Server controls dynamically on webform and validating them by binding events

Sample Image - DynamicServerControls.jpg

Introduction

Generally in majority of the cases the ASP.NET server controls were placed onto the webform during design time and the developer will be working with the controls he has bind to the form during design time.I came across a situation where in there is a need to create the ASP.NET server controls on the fly.

Consider a situation where there is necesicity to create the n number of textbox dynamically. The number of textbox is not decided and is driven by some other criteria.

Methodlogy :So the wholething can be organised by following way.

1)Decide the type of .NET server controls one need to create on fly and Creation of these controls and binding to the webform (Webform1.aspx)

In our case we are going to create the following controls dynamically.

a)TextBox control

b)Button control

Introduction

For the same create a webform for the new ASP.NET project and provide a textbox field which gives the number of TextBox created dynamically on the webform.When user enters a number in the textbox and clicks on button "add textbox" button textbox number the user entered will be created dynamically.

Strategy

A placeholder is added during design time and the dynamically created server controls added to the placeholder.

-> Create a table instance

Table tblHead = new Table();

->Check if is of type table and place holder is not having any table instance then add a table to the placeholder to add a literal text to the created table.

if (tblHead.GetType().ToString().Equals("System.Web.UI.WebControls.Table") && PHOptions.FindControl("tblHead") == null )

{

tblHead.ID = "tblHead";

tblHead.EnableViewState = true;

tblHead.BorderWidth=Unit.Pixel(0);

tblHead.CellSpacing = 0;

tblHead.CellPadding = 1;

tblHead.Width = Unit.Percentage(96);

TableRow rH = new TableRow();

TableCell cH = new TableCell();

cH.Text= "Table Heading" ;

cH.Font.Bold = true;

rH.Cells.Add(cH);

tblHead.Rows.Add(rH);

PHOptions.Controls.Add(tblHead);

if(intColCount>0)

rH.Visible =true;

else

rH.Visible =false;

}

->For the created table instance ID assigned as "tblHead"

tblHead.ID = "tblHead";

->Table row is added and a cell is added .Cell is bound to row, row to table and table to place holder in sequential manner.

The above steps demonstates addition of a literal text "Table Heading" to a dynamically created table which is added to the PlaceHolder.

->Having created a table dynamically and adding to placeholder same process can be repeated to create the number of text box user has entered in the "Number of Textbox controls" TEXTBOX.

Table tblHelp = new Table();

if (tblHelp.GetType().ToString().Equals("System.Web.UI.WebControls.Table") && PHOptions.FindControl("tblHelp") == null )

{

tblHelp.ID = "tblHelp";

}

tblHelp.EnableViewState = true;

tblHelp.BorderWidth=Unit.Pixel(1);

tblHelp.CellSpacing = 0;

tblHelp.CellPadding = 1;

tblHelp.BorderWidth = Unit.Pixel(1);

tblHelp.Width = Unit.Percentage(96);

for (int rowIndex=0; rowIndex<=rowCount; rowIndex++)

{

TableRow r = new TableRow();

TableRow rWeight= new TableRow();

//r.ID = "rLabel";

TableRow rID = new TableRow();

for (int clIndex=0; clIndex<intColCount; clIndex++)

{

TableCell c = new TableCell();

txtBox = new TextBox();

if (txtBox.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox") && PHOptions.FindControl("txtOption"+(clIndex+1).ToString()) == null )

{

txtBox.ID ="txtOption"+(clIndex+1).ToString();

//txtBox.Text = (clIndex+1).ToString();

txtBox.Width= Unit.Pixel(45);

txtBox.MaxLength = 2;

c.BorderWidth=Unit.Pixel(1);

c.Width=Unit.Pixel(80);

c.Controls.Add(txtBox);

r.Cells.Add(c);

txtBox.PreRender += new System.EventHandler(this.txtBox_PreRender);

}

}

tblHelp.Rows.Add(r);

}

->Create a table and name it as "tblHelp".

->Add Table Row

TableRow r = new TableRow();

->Add Table Cell

TableCell c = new TableCell();

->Key point is iterate in a loop create as many cells as the user input the number of text box in TEXTBOX control. Create the instances of TEXTBOX object that has been declared in declaration section.

protected System.Web.UI.WebControls.TextBox txtBox;

Create instances out of the textbox object and add the control to cell objects that have been created.

txtBox.ID ="txtOption"+(clIndex+1).ToString();

c.Controls.Add(txtBox);

->Finally bind the row to the table.

tblHelp.Rows.Add(r);

->Repeat the process to attach the dynamic button called submit

2)Carrying out the validation on the dynamically created controls.

Introduction

For this events to be attached to each one of the dynamically created control. For example in our example if we have decided to create 4 textbox and we checking non nullability on those 4 textbox, Prerender event has to be attached to these 4 dynamically created server controls.

Strategy

->Having created the controls dynamically and bind to the form we now carry out the validation on these created controls(check for non nullablity)

After binding the control attach the Prerender event to the textbox object

txtBox.PreRender += new System.EventHandler(this.txtBox_PreRender);

and Click even to Button object.

this.btnSubmitButton.Click += new System.EventHandler(this.btnSubmitButton_Click);

In prerender event send the textbox object name as arguement to client side javascript function for validation

In Click event just append the values the user entered in dynamically created textbox.

Conclusion

Likewise we can attach any server controls to the webform dynamically and attach the events on the created server cotrols as per the requirement.

I made use of this strategy to represent 3X3 matrix data on the form and the updated info is saved to the database.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
India India
Involved in developing MS applications for last 4.4 Yrs lately into ASP.NET and C#.NET

Comments and Discussions

 
GeneralGreat Pin
Sachin Gururaj18-Sep-07 0:59
Sachin Gururaj18-Sep-07 0:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.