ASP.Net Dynamic Controls (Part 4)
I’ve had several people ask about redrawing a page that contains Dynamic Controls. The idea is that you have a page with a “Save” button that posts back but the page reloads exactly as it was. You can think of it like the “Apply” button in Windows but on a web page. The heart of the issue is what is the proper way to redisplay the data in the dynamic controls since they don’t have a viewstate.
In fact they do seem to have a viewstate but only if you regenerate the control exactly as it was before the post back. So if you create a checkbox with an ID of chkbox1 during Page_Load, after post back recreate it again during Page_Load with the same ID and it will repopulate from the viewstate. So you don’t need to use Request.Form to get the values and repopulate by hand which is a major plus.
<%@ Page Language="VB" %>
<script runat="server">
Sub Page_Load()
lblMessage.Text = ""
If chkRegen.Checked Then
Dim rnd As New Random(Date.Now.Millisecond)
Dim chk As CheckBox
Dim num As Integer
' Generate dynamic controls
For i As Integer = 1 To 10
' Generate a checkbox
chk = New CheckBox()
If chkRandom.Checked Then
num = rnd.Next
chk.ID = "chk" & num
chk.Text = "Checkbox " & num
Else
chk.ID = "chk" & i
chk.Text = "Checkbox " & i
End If
' Add the checkbox to the placeholder
phControls.Controls.Add(New LiteralControl("<div>"))
phControls.Controls.Add(chk)
phControls.Controls.Add(New LiteralControl("</div>"))
Next
End If
End Sub
Sub Click_Save(ByVal s As Object, ByVal e As EventArgs)
lblMessage.Text = "Clicked Save"
End Sub
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Dynamic Control Test</title>
<style type="text/css">
body { font-family: verdana, sans-serif; }
div { padding: 5px; }
</style>
</head>
<body>
<h1>ASP.Net Dynamic Controls (Part 4) Demo</h1>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSave" OnClick="Click_Save" Text="Save" runat="server" />
<asp:Label ID="lblMessage" runat="server" />
</div>
<div><asp:CheckBox ID="chkRegen" Text="Regenerate Dynamic Controls" Checked="true" runat="server" /></div>
<div><asp:CheckBox ID="chkRandom" Text="Use Different IDs" runat="server" /></div>
<asp:PlaceHolder ID="phControls" runat="server" />
<div><h2>Request.Form Contents</h2><dl>
<% Dim str As String
For Each str In Request.Form.AllKeys
Response.Write("<dt>" & str & "</dt><dd>" & Request.Form(str) & "</dd>")
Next
%>
</dl></div>
</form>
</body>
</html>
The sample code above shows off this working. There are a total of twelve checkboxes the first two are settings for the post back and the remainder are the dynamic controls. If you uncheck “Regenerate Dynamic Controls” and click save you will see that the checkboxes disappear but data remains in the Request.Form collection. Also if you check “Use Different IDs” it will randomly generate the IDs and the controls will not be repopulated, the ID must be the same for repopulation.
ASP.Net Dynamic Controls (Part 1) «
ASP.Net Dynamic Controls (Part 2) «
ASP.Net Dynamic Controls (Part 3) «
Categories
Recent
- Browser Logo Shootout
- Blackberry Surreal Theme
- Blackberry JDE API - User Interface Field Reference
- Getting started with the Blackberry Java Development Environment (JDE)
- ASP.Net DropDownList annoyance
- Getting a Blackberry Curve
- Mambo to the beat of the internet
- ASP.Net has 9 to 5 appeal
- ASP.Net CheckBoxes should be able to have values
- Time to take a look at Python I guess
- Country list formatted for MySQL import
- Kinetic Typography: typographic treatment of an audio sample
- MSN Video Sucks
- Five things about me
- Blackberry MP3 Player Instructions



hi,
I liked your blog and would like to ask a question. I am trying to call a Javascript function with 2 paramaters when someone click a linkButton in gridView. My code looks like this:
OnClientClick =”DisplayPopUp(’ImagePopup.aspx’, ‘<%=”SomeUniqueValue”%>’);”
but I am getting some error in it because of ” saying the server tag is not well formed. Is there any way to resolve this thing?
Thanks
Raj
You can’t dynamically change a static control (<asp:XXXX controls are static). These types of controls are compiled before the code on the page runs so having a code block <% %> in them will cause a syntax error during compilation.
Your best bet is to use a standard HTML input tag which is not compiled and will allow for code block insertion.
Thank you. I never fill these things out, but I have spent the past two days trying to wrap my head around this concept. You answered for me in one article what I could not locate anywhere else.
Hi, I read your blog. And it is really helpful. But I dont wantto create controls in a for loop in my Page_Load.
I have a case like; User selects “DataGrid” or “TextBox” or “CheckBox” from a dropdownlist and presses to a button. Every button click i need to add a textbox or a checkbox (what user selects.) to my placeholder. I could not find a solution to this.
The only solution that i found is: to add all current controls (and their values) to session after adding to placeholder. And in every page load to get controls from Session and add to page one by one..
Is there any other way? I dont want to do like that.
I thought Part 4 was supposed to be about AJAX? Looks like that one got ya stumped, eh? ;-)
Just as an FYI, as a writer, you really ought to refactor this series of articles. Most programmers are interested in the right way to do something, and why it’s right. You have whole articles (Part 1 and Part 2?) that essentially tell people the wrong way to do things…so why would you want someone to read that?
Kindly tel me how to add this handler in c#(c# code)
AddHandler cmd.Click, AddressOf Button_Click
C# Equivalent:
Thanks so much for posting this; it helped me quickly solve an issue I’ve been struggling with! ~ Sue
Here is an example of pulling from the database and processing the ids in the save click.
Extremely Helpful Adam!!!!
Thank you SIR! Saved me many hours of headaches…
Great Hints,
I have using one day to think about how to prevent dynamic control disappear after post back and maintenance the viewstate.
It seem i just leave it re-generate every times on Page_Load and keep the same ControlID is the easy way to solve my problem.
Hai.
Is there any posibility to generate complete grid view in dynamic means withour html source. using only code behind. if yes..
add drop downlist and checkbox from coding
Hi, I’ve been reading your posts and are great but I have a question to help me in my development. I’m trying to add panels dynamically with out clear the previous. I mean initially I have just 1 panel with some textboxes, in the bottom of the page I have a Button to “Add a new panel”, ok i just want to click that button and render in my page a new panel without deleting de previous one, and if i have added 3 panels when i click the fourth time the button get the 4 panels rendered in the page. This can be done?? Thanks for your support!!!!