I have seen a lot on articles on the web for generating controls dynamically in asp.net page and retaining them on postback. But all of the articles seems to be quite complex. I just wanted to make the whole thing somewhat simpler. So check if this seems to be a simple way out to do that.
I shoult tell you the steps involved in generating controls dynamically
- Add a
Table/Div container to the aspx page
- Have a collection of contol IDs as a Viewstate-backed property in code-behind. I have used Generic List here as
- On the 'Add Control Button' click event's eventhandler, add the new ID to this list. Make sure that these IDs are unique
Page_PreRender generate the controls on the basis of these unique ids
Using the code
To add a control on a Postback event(Say, click of a button), we have to generate that control in code. And then add it to a container like div or table, which must be already present in the aspx page. Like
CreateATableRow function in the code does that like:
Dim rowAdditional As New TableRow()
rowAdditional.ID = textName + "ROWID"
Dim cellAdditinal As New TableCell()
cellAdditinal.ID = textName + "CELLID"
Dim textAdditional As New TextBox()
textAdditional.ID = textName + "TEXTID"
textAdditional.Text = textName
All the previous added controls IDs are maintained as a generic list as
List(Of String) so as to add them at page rendering. List is also beneficial because we have to check that the new control ID does not exist already, which can be done by checking
Contains function of that list like:
After that all the contol IDs existing in AdditionalEnteries list are just rendered on Page_PreRender.
For Each keyEntry As String In AdditionalEnteries
If Not String.IsNullOrEmpty(keyEntry) Then
Things done!!! Happy Coding.
Points of Interest
Using of generic is optional here. But use of them make a lot of thing easier a lot of time, including this
- Modified the language to make the reading easier.