How to Create and Read Values of Dynamic Controls in ASP.Net

I have searched for and found many websites but they do not show how to read values of dynamically created controls, only how to create dynamic controls in ASP.Net.

So today I will show to how to create dynamic controls in ASP.Net and how to read the dynamically created control values using ASP.NET. In this article, I have dynamically created "TextBox", "DropDownList", "RadioButtonList" and "CheckBoxList" contorls.
For better understand, please download the source code form this article.

The following shows how to to create a dynamic TextBox and read its value.

.ASPX Code

Dynamic-Controls-1.jpg

C# Code

Dynamic-Controls-2.jpg

Read TextBox Value

Dynamic-Controls-3.jpg

Example

Dynamic-Controls-4.jpg

The following shows how to to create a dynamic DropDownList and read its value.

.ASPX Code

Dynamic-Controls-5.jpg

C# Code

Dynamic-Controls-6.jpg

Read DropDownList Value

Dynamic-Controls-7.jpg

Assign SelectedIndexChange Event to DroupDownList

Add the "ddl_SelectedIndexChanged" event to the droupdownlist dynamically using the following code:

Dynamic-Controls-8.jpg

Dynamic-Controls-9.jpg

Example

Dynamic-Controls-10.jpg

The following shows how to to create a dynamic RadioButtonList and read its value.

.ASPX Code

Dynamic-Controls-11.jpg

C# Code

Dynamic-Controls-12.jpg

Read RadioButtonList Value

Dynamic-Controls-13.jpg

Example

Dynamic-Controls-14.jpg

Create dynamic CheckBoxList and read their value:

.ASPX Code

Dynamic-Controls-15.jpg

C# Code

Dynamic-Controls-16.jpg

Read CheckBoxList Value

Dynamic-Controls-17.jpg

Example

Dynamic-Controls-18.jpg

Dynamically Created Controls Losing Data After Post-back or Retaining State for Dynamically Created Controls in ASP.NET Applications

Before we proceed, we need to keep in mind one thing. When you create a dynamic control in a page and if you do a post-back then the created control will be lost. I mean to say that "When using dynamic controls, you must remember that they will exist only until the next post-back. ASP.NET will not re-create a dynamically added control". You need to recreate all dynamically created controls on every post-back (in load event at the latest). You also need to ensure that they get the same ID as before to trigger events and maintain View State.

To show this issue I have used the following code:

Dynamic-Controls-19.jpg


Similar Articles