Dynamically creating ASP.NET controls from the code behind files


This article demonstrates how you can dynamically generate ASP.NET controls in runtime using the code behind code and access the properties of the dynamically created controls.

Dynamically creating ASP.NET controls


ASP.NET is a very powerful and flexible technology, allowing programmers to develop sophisticated web applications within a short period of time. It is so easy to drag and drop controls in a web form and start writing the business logic in the code behind file.
Ofcourse, dragging and dropping controls from the toolbox is the easiest approach. But sometimes we may need to generate ASP.NET controls in the server side using the VB.NET or C# code. For example, consider a case where you are developing an application where you want to display a list of checkboxes to the user, depending on the number of records in a database table. In this case, you cannot drag and drop few checkbox controls, because you will not know how many checkboxes you are going to need until you retrieve the records from the database.

In this article, I will discuss how you can create ASP.NET controls at runtime using C# syntax. You can easily convert this to VB.NET syntax with little effort.
Create a new ASP.NET web application using Visual Studio.NET. It will create a sample web page with the name webform1.aspx. Let us use this page for our experimentation.
Drag and drop a panel control into the webform. We will dynamically generate a checkbox and add to this panel.

Double click on the webform1.aspx page. This will add a page load event handler in the code behind file. Add few lines of code in the Page_Load event handler as shown below:

private void Page_Load(object sender, System.EventArgs e)
{
CheckBox _checkbox = new CheckBox();
_checkbox.ID = "chkDynamicCheckBox";
_checkbox.Text = "This is a dynamically generated checkbox";

Panel1.Controls.Add (_checkbox);
}

The above code will create a checkbox dynamically and add to the panel in the form. Using this approach, you can create any other ASP.NET control during runtime and add to the form.

How to specify a position for the dynamically dynamically created ASP.NET control?


The most common method is to use <table> to position controls and text in html. In our case, since we are dynamically generating the controls, we may want to use ASP.NET table control to dynamically create rows and cells in the table and add our dynamic controls into it.
Drag and drop an ASP.NET table control into the form and give it the name 'tblDynamic'. Now, go back to the Page_Load event handler in the code behind file. The following code sample will create 5 textboxes and labels. We will create 5 rows and 2 cells in each row dynamically and add our dynamicaly created textbox/label controls to the table so that they will be aligned properly and will appear in the page in proper format.

private void Page_Load(object sender, System.EventArgs e)
{
for ( int i = 0; i < 5; i++ )
{
TableRow tr = new TableRow();
// Create column 1
TableCell td1 = new TableCell();
// Create a label control dynamically
Label _label = new Label();
_label.ID = "lbl" + i.ToString();
_label.Text = "Enter Value " + i.ToString();
// Add control to the table cell
td1.Controls.Add(_label);

// Create column 2
TableCell td2 = new TableCell();
TextBox _text = new TextBox();
_text.ID = "txt_" + i.ToString();
// Add control to the table cell
td2.Controls.Add(_text);
// Add cell to the row
tr.Cells.Add(td1);
tr.Cells.Add(td2);
// Add row to the table.
tblDynamic.Rows.Add(tr);
}
}

How to access the dynamically created ASP.NET controls?


If we drag and drop controls to the web form, the designer automatically generates some code in the aspx page, gives an id to the control and creates the required declarations in the code behind file. This allows us to easily access the control from code behind file and set/get any of it's properties.

But what will happen to the controls created during runtime? How can we access it's properties?

The easiest way to access these dynamically created textboxes is, iterate through all controls in the form and check if it is textbox. In the above example, we have prefixed the ID with "txt_" and then appended the serial number to it for all dynamically generated controls.

Use the following recursive function to iterate through the list of all controls in the form. We are passing the form itself as parameter to the the function. The function will iterate through all children of the passed control and checks if the child control is a textbox and if the id starts with "txt_". If it matches, it sets the Text property to "You Got It!"

void IterateControls(Control parent)
{
foreach (Control child in parent.Controls)
{
if (child.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox")
&& child.ID.IndexOf("txt_") == 0)
{
TextBox textbox = (TextBox)child;
textbox.Text = "You Got It !";
}

if (child.Controls.Count > 0)
{
IterateControls(child);
}
}
}

How to test it?
Add the above method to your code behind file. Drag and drop a button control to the form and double click on it to create a button clicked event handler. Call the above method from the button click event handler as shown below:

IterateControls(this);

Now, run the application and see. When you launch the application, it will dynamically create 5 textboxes and when you click on the button, it will populate the value 'You Got It !" in all the dynamically created textboxe controls.


Comments

Author: pappu17 Dec 2004 Member Level: Bronze   Points : 0

It is one of the best Articles for freshers....

Author: Geetha Gopi16 Jan 2005 Member Level: Bronze   Points : 0

Hi, I am trying to convert this to vb.net. I am having a doubt in the IterateControls function. the parameter parent, where i have to declare that and what data type is it. I am a beginner for .net. please help me.

Author: Tony John17 Jan 2005 Member Level: Gold   Points : 0

The parameter 'parent' is of type 'Control'. In VB.NET you can declare it as

private sub IterateControls(ByVal parent as Control)
---
end sub

Author: Siddesh Kapadi15 Apr 2005 Member Level: Bronze   Points : 0

this code doesnot work as the values dont get displayed in my textboxes.

Author: anupam thakur09 May 2005 Member Level: Bronze   Points : 0

i tries all this but i'm unable to get values which i enter at run time from the text boxes also when i press some button the dynamically generated controls are lost

Author: Nataraj22 May 2005 Member Level: Silver   Points : 0

This is very much helpful to create a controls at runtime.Code is working fine

Author: navinkumar27 May 2005 Member Level: Bronze   Points : 0

I love this article.

Thankyou.

Author: Kevin Wison24 Aug 2005 Member Level: Silver   Points : 0

This is an excellent article for a novice.
Keep it up!

Author: Besnik Shehu25 Nov 2005 Member Level: Bronze   Points : 0

I have a page that uses the above code, but I'm running into problems.

It works like this. The user is asked how many names they need to submit, and then two textboxes are created dynamically based on the number the user chooses.

The problem is that on postback those controls are lost, and the information typed on the controls is lost. How do I prevent that what happening, and how can I retrieve the data on Postback, that was entered on the dynamically created controls?

Thanks

Author: mallika04 Jun 2007 Member Level: Bronze   Points : 0

its coming out of the For loop..Not working

Author: nitin23 Jun 2007 Member Level: Silver   Points : 0

No doubt ur code is working properly but if i want to place textbox only in both cell then textbox willhave same ID ?
pls mail me the ans

Author: guruank07 Aug 2007 Member Level: Bronze   Points : 0

I am having problems with accessing the created controls when i try to access them them they post back and the page becomes blank once again..

plzzzzzz help

Author: Pavan B18 Feb 2008 Member Level: Silver   Points : 0

The code works for the first time. Suppose we have to create 4 text boxes repeatedly. The code works only for the first time. We can't create the 4 textboxes repeatedly.
Also not possible to resize the textboxes.

Author: DaRocker2226 May 2008 Member Level: Bronze   Points : 2

Put your code in OnInit instead of Page load so you when you do a postback the controls don't get rebuilt and set back to the default values and lose the postback data.

protected override void OnInit(System.EventArgs e) {
// Dynamic code goes here
}

Author: mehdi02 Nov 2008 Member Level: Bronze   Points : 2

Dear Sir
I used of the your article(Dynamically creating ASP.NET controls from the code behind files).
It was very excellent. but I have a question:
I used of object control RadioButtonList ,It works perfectly in IE browser, but when I'm viewing the same page using Firefox, the radiobuttonlist's selected values,selected index are lost after a postback.
my code is following:

protected void Page_Load(object sender, EventArgs e)
{
TableRow tRow1 = new TableRow();
TableCell tCell1 = new TableCell();
TQuestion.Rows.Add(tRow1);
Label _label = new Label();
_label.ID = "lbl-one_selection1";
_label.Text = "---";
tRow1.Cells.Add(tCell1);
tCell1.Controls.Add(_label);

TableRow tRow2 = new TableRow();
TableCell tCell2 = new TableCell();
TQuestion.Rows.Add(tRow2);
RadioButtonList _radio = new RadioButtonList();
_radio.ID = "rad-one_selection1";
char[] delimiterChars = { '\n' };
string[] words;
string strdb = TextBox2.Text;
words = strdb.Split(delimiterChars);
foreach (string s3 in words)
{
_radio.Items.Add (new ListItem(s3, s3));
}
_radio.RepeatDirection = RepeatDirection.Vertical;

tRow2.Cells.Add(tCell2);
tCell2.Controls.Add(_radio);


}
protected void Button2_Click(object sender, EventArgs e)
{
IterateControls(this);
}
void IterateControls(Control parent)
{
string IdQuestion;

foreach (Control child in parent.Controls)
{
if (child.GetType().ToString().Equals("System.Web.UI.WebControls.RadioButtonList") && child.ID.IndexOf("rad-one_selection") == 0)
{
RadioButtonList textAnswer3 = (RadioButtonList)child;
IdQuestion = Convert.ToString(child.ID).Substring(17);

TextBox1.Text = Convert.ToString(textAnswer3.SelectedIndex +1);
}

if (child.Controls.Count > 0)
{
IterateControls(child);
}
}
}

Author: M.Nazeer Ahamad26 Jun 2009 Member Level: Bronze   Points : 2

Respected sir,
i have used your code(in VB.net), it is working fine....
i have given your code in buttonclick event and when ever i click it for the first time then it will work fine and if i click the button next time then the old generated controls are not coming(i think it is overwriting, in page sources also they are not available )... so can you give me a solution how generate the new controls with out loosing the old controls....

thanks for ur code...

Author: Taiseer Hussein25 Feb 2010 Member Level: Bronze   Points : 1

Dear Tony John,
Thank you very much for this article. This is what exactly I was looking for. You solved a big issue for me.

Thanks
Taiseer

Author: Sona27 Feb 2010 Member Level: Silver   Points : 0

I like this article.

Author: bhupal27 Jul 2010 Member Level: Bronze   Points : 1

dear Tony John,

it is good as per page load but i changed the place of code to the button click event the page is blank so can you please help me how to stop that controls to be from invisible

bhupal

Author: Rajkumar Pomaji28 Jul 2010 Member Level: Gold   Points : 1

Hey one the best code to access Asp.net controls
Dynamically..

Thanks and Regards
Rajkumar Pomaji

Author: Biju04 Aug 2010 Member Level: Gold   Points : 2

private DataTable GetExcelData(string NewFilePath)
{
DataTable ExcelDataTable = new DataTable();
OleDbConnection OleDbCon = null;
try
{
//string strSourcePath = System.AppDomain.CurrentDomain.BaseDirectory + @"\Upload\" + strFileName;
string strConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + NewFilePath + ";" + "Extended Properties=Excel 8.0;";
// string strConnectionString = ConfigurationSettings.AppSettings[@"XLProvider"] + strFileName + ConfigurationSettings.AppSettings[@"XLProperties"];
OleDbCon = new OleDbConnection();
OleDbCon.ConnectionString = strConnectionString;
OleDbCon.Open();
string[] strArray = GetExcelSheetNames(NewFilePath);
OleDbCommand oleDbCommand = new OleDbCommand("Select * from [" + strArray[0] + "]", OleDbCon);
oleDbCommand.Connection = OleDbCon;
OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter(oleDbCommand);
oleDbDataAdapter.Fill(ExcelDataTable);
}
catch (Exception ex)
{
Message= ex.Message;
}
finally
{
// Clean up.
if (OleDbCon != null)
{
OleDbCon.Close();
OleDbCon.Dispose();
}
}
return ExcelDataTable;

}

Author: Biju04 Aug 2010 Member Level: Gold   Points : 2

public static String[] GetExcelSheetNames(string excelFile)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
// Connection String. Change the excel file to the file you
// will search.
String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
// string connString = ConfigurationSettings.AppSettings[@"XLProvider"] + excelFile + ConfigurationSettings.AppSettings[@"XLProperties"];
// Create connection object by using the preceding connection string.

objConn = new OleDbConnection(connString);
// Open connection with the database.
objConn.Open();
// Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

if (dt == null)
{
return null;
}

String[] excelSheets = new String[dt.Rows.Count];
int i = 0;

// Add the sheet name to the string array.
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheets;
}
catch (Exception ex)
{
return null;
}
finally
{
// Clean up.
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}

Author: Biju05 Aug 2010 Member Level: Gold   Points : 2

public class ConvertType
{
public ConvertType(object obj);

public static implicit operator byte(ConvertType str);
public static implicit operator float(ConvertType str);
public static implicit operator decimal(ConvertType str);
public static implicit operator double(ConvertType str);
public static implicit operator string(ConvertType str);
public static implicit operator bool(ConvertType str);
public static implicit operator short(ConvertType str);
public static implicit operator DateTime(ConvertType str);
public static implicit operator float?(ConvertType str);
public static implicit operator long?(ConvertType str);
public static implicit operator bool?(ConvertType str);
public static implicit operator decimal?(ConvertType str);
public static implicit operator int?(ConvertType str);
public static implicit operator long(ConvertType str);
public static implicit operator int(ConvertType str);
}





public static Int64 ConvertDateTimeToBigInt(string strInput)
{
if (!string.IsNullOrEmpty(strInput))
{
string[] dd = strInput.Split('/');
strInput = dd[0] + "/" + dd[1] + "/" + dd[2];
string dt1 = strInput.Substring(6, 4) + strInput.Substring(3, 2) + strInput.Substring(0, 2);

return new Interlace.Utils.ConvertType(dt1);
}
else
{
return 0;
}
}





public static string ConvertBigIntToDateTime(string strInput)
{
if (strInput.Length >= 8)
{
int year = new Interlace.Utils.ConvertType(strInput.Substring(0, 4));
int month = new Interlace.Utils.ConvertType(strInput.Substring(4, 2));
int day = new Interlace.Utils.ConvertType(strInput.Substring(6, 2));
DateTime dt = new DateTime(year, month, day);
return dt.ToString("dd/MM/yyyy");
}

return string.Empty;

}



public static string ConvertBigIntToDateTime(string strInput)
{
if (strInput.Length >= 8)
{
int year = new Interlace.Utils.ConvertType(strInput.Substring(0, 4));
int month = new Interlace.Utils.ConvertType(strInput.Substring(4, 2));
int day = new Interlace.Utils.ConvertType(strInput.Substring(6, 2));
DateTime dt = new DateTime(year, month, day);
return dt.ToString("dd/MM/yyyy");
}

return string.Empty;

}



public static string ReturnTimeString(object value)
{
if (float.Parse(value.ToString()) > 0)
{
string AmPm = "AM";
int valHH = int.Parse(value.ToString());
int valMM = int.Parse(value.ToString());

valHH = valHH / 60;
valMM = valMM % 60;

if (valHH >= 12)
{
if (valHH >= 24)
{
valHH = valHH - 24;
AmPm = "AM";
}
else
{
if (valHH > 12)
valHH = valHH - 12;

AmPm = "PM";
}

}

string strHH = valHH.ToString();
string strMM = valMM.ToString();

if (valHH < 10)
strHH = "0" + strHH;
if (valMM < 10)
strMM = "0" + strMM;

return strHH + ":" + strMM + " " + AmPm;
}
else
return "0:0";
}




public static string GetDate(Object date)
{
string formattedval = string.Empty;
if (date != null && date.ToString() != string.Empty)
{
String dateFormat = date.ToString();
formattedval = dateFormat.Substring(6, 2) + "/" + dateFormat.Substring(4, 2) + "/" + dateFormat.Substring(0, 4);
}
return formattedval;
}




public static string ConvertDataRowtoString(DataTable dtRow, string HeaderName, string Condition)
{
String[] Name = Array.ConvertAll(dtRow.Select(Condition), delegate(DataRow Datrow) { return Datrow[HeaderName].ToString(); });
string Concatenate = string.Join(",", Name);
return Concatenate;
}

public static string ConvertRowtoString(DataTable dtRow, string HeaderName, string Condition)
{
String[] Name = Array.ConvertAll(dtRow.Select(Condition), delegate(DataRow Datrow) { return Datrow[HeaderName].ToString(); });
string Concatenate = string.Join(", \n", Name);
return Concatenate;
}



Guest Author: gaurav15 Apr 2012

i want to add a button and a label to my asp.net webpage dynamically and want to set the text property of that label through click event of that dynamically generated button...
can u help me with dat???

Guest Author: purvi27 Apr 2012

Thanks for the info... just what i needed...

Guest Author: Ghulam Haider07 Nov 2012

Excellent.....!

Author: ketan Italiya04 Aug 2013 Member Level: Gold   Points : 0

it is so helpful thanks...

Author: Ranajoy11 Aug 2013 Member Level: Silver   Points : 0

Good Article.But, also include some more codes with PlaceHolder, Literal and Repeater.

Otherwise, it is very good article for beginners.

Author: Phagu Mahato06 Jan 2014 Member Level: Gold   Points : 10

You may require to create controls dynamically in ASP.NET. Because of the ASP.NET page life cycle.After that you need to write the C# code in Page Load event or button event as follows :


Panel1.Controls.Add(new LiteralControl(“
"));

Panel1.Controls.Add(new LiteralControl(“"));

Panel1.Controls.Add(new LiteralControl(“
"));

private void CreateDynamicControls(int count)
{
for (int i = 0; i < count; i++)
{
var textBox11 = new textBox1();
var textBox1Cell = new TableCell();
var tableRow = new TableRow();
tableRow.Cells.Add(textBox1Cell);
textBox1Cell.Controls.Add(textBox1);
tblRecipients.Rows.Add(tableRow);
}
}



Method to Generate dynamic controls




public static DynamicControl GenerateControl(FormControlsBO bo)
{
DynamicControl dynamicControl = new DynamicControl();
Control control = new Control();

LiteralControl literal = new LiteralControl();

switch (box1.FieldType)
{
case "TextBox":
control = new TextBox();
control.ID = box1.FieldName;
literal.Text = bo.FieldLabel;
break;
case "RadioButton":
control = new RadioButton();
control.ID = box1.FieldName;
literal.Text = box1.FieldLabel;
break;
case "CheckBox":
control = new CheckBox();
control.ID = box1.FieldName;
literal.Text = box1.FieldLabel;
break;
case "DropDownList":
control = new DropDownList();
control.ID = box1.FieldName;
literal.Text = box1.FieldLabel;
break;
}

control.ClientIDMode = ClientIDMode.Static;
dynamicControl.GeneratedControl = control;
dynamicControl.GeneratedControlLiteral = literal;
return dynamicControl;
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: