Monday 6 August 2007

ASP.NET - Dynamic Controls

Let's say you wanted to create a CheckBox for every row in a table. How do we create it? How do we reference it on a PostBack? There are many guides on how to do this but they are unclear and don't explain what happens.

If we create components via code, you may be unsure on how to reference it later, say in a buttons click. When they are created dynamically the problem is that the controls are lost on a PostBack thus code fails to execute and you can't get the Checked state or Text of say a TextBox control because they are no longer there.

How do we solve this? You MUST create all dynamic controls in the Page_Init event. This means that the controls will not be lost during a PostBack, thus you can reference them correctly.

Let's create 10 CheckBox controls on the page and then return their checked state when you push a button. The first thing to do is place a PlaceHolder control onto the page, in this example it will be left to its default name of PlaceHolder1. This will be a container for all of our dynamic controls.


dim i
for i = 0 to 9
Dim cb As New CheckBox
cb.ID = "cb" & i
cb.Text = "Dynamic Checkbox " & i
cb.EnableViewState = True
cb.Width = 300
PlaceHolder1.Controls.Add(cb)
PlaceHolder1.Controls.Add(New LiteralControl("< BR>"))
Next


In the example above we step through a loop and create 10 checkbox controls, each with a html break to seperate them and make it look tidy. Now all we need to do is get the state of every checkbox and here's how (place the following code within a button):



Dim results
Dim cb As Control
For Each cb In PlaceHolder1.Controls
If TypeOf cb Is CheckBox Then
If CType(cb, CheckBox).Checked Then
results = results & CType(cb, CheckBox).Text & " is Checked < BR>"
End If
End If
Next
response.write(results)


The above will simply check through all of the dynamic controls and list all the boxes that are checked via a simple response.write. You could code a Select All button simply by doing the following:



Dim cb As Control
For Each cb In PlaceHolder1.Controls
If TypeOf cb Is CheckBox Then
CType(cb, CheckBox).Checked = True
End If
Next


Easy! Hopefully you all understand the basics of working with dynamic controls now. The examples above have no limit on the amount of controls that are created and can easily be adapted to the amount of rows on a database, for example.

No comments: