Thursday, August 2, 2007

Dynamic Control Generation in ASP.NET

The Code is written in VB.NET
1.Place a DropDown web server control and name it "ddlCount", right click Edit Items and add values as many numeric values as you want to.
2.Place a Button web server control and name it "btnGenerate"
3.Place a Label web server control and name it "lblDynamics" , clear its TEXT property
4.Place a Button web server control and name it "btnRead"
5.Place a Label web server control and name it "lblData", clear its TEXT property

On the code behind file copy the following code

Public Sub generateControls(ByVal count As Integer)
lblDynamics.Text = ""
Dim i As Integer
For i = 1 To count
lblDynamics.Text += ""
Next
lblDynamics.Text += "< table > < tbody > < tr > < td > %lt; input name="'txtControl" id="'txtControl" style="" type="text'"> Control Number " + i.ToString() + "</td> </tr> </tbody > < /table>"
End Sub

Public Sub readData()

End Sub

'Double click the btnGenerate button to get its click event, see following code

Protected Sub btnGenerate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGenerate.Click
generateControls(Convert.ToInt32(ddlCount.SelectedValue.ToString()))
ViewState("controlCount") = ddlCount.SelectedValue.ToString()
End Sub


'Double click btnRead button to get the click event, see following code
Protected Sub btnRead_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRead.Click
Dim i As Integer
lblData.Text = ""
For i = 1 To Convert.ToInt32(ViewState("controlCount").ToString())
'Request.Params["txtRequested" + zoneno]
lblData.Text += "You typed: " + Request.Params("txtControl" + i.ToString()).ToString() + " in " + i.ToString + " control."
Next
End Sub