Adding and binding dynamic webcontrols to web form from database
1.In your aspx, first add a placeholder (to hold all your dynamic controls)
2.Import system.data and initialise a datatable as below
Imports System.Data ' Import this first
Dim DT As DataTable ' Initialise a datatable
3.Then create method.function like below to create and bind dynamic controls.
Protected Sub AddControl()
DT = New DataTable()
DT = YourDatatable ' Here you assign your datatable, that holds values from sql server
Dim i As Integer = 0
If DT.Rows.Count > 0 Then
Dim dr As DataRow
For Each dr In DT.Rows
Dim srno As New Label ' Here I am creating dynamic labels to show serial numbers
srno.ID = "Label_" + i.ToString()
srno.Text = (i + 1).ToString() + " . "
Me.PlaceHolder1.Controls.Add(srno) ' Finally i added the created control to place holder
Dim DynamicLabel As New Label ' Here I am creating dynamic labels to show label text from datatable
DynamicLabel.ID = "Label2_" + i.ToString()
DynamicLabel.Text = dr("MCM_MACHINE_TAG").ToString.Trim() ' Here instead of "MCM_MACHINE_TAG" , you have to put your datafield
Me.PlaceHolder1.Controls.Add(DynamicLabel) ' Finally i added the created control to place holder
Dim MyLiteral2 = New LiteralControl 'Here I added a dynamic break after the label control
MyLiteral2.Text = "
"
Me.PlaceHolder1.Controls.Add(MyLiteral2) ' Finally i added the created control to place holder
Dim dynamicRadioButton As New RadioButton ' Here I am creating dynamic Radio button to show data from datatable
dynamicRadioButton.ID = "RadioButton_" + i.ToString()
dynamicRadioButton.Text = dr("MCM_MODEL").ToString.Trim() ' Here instead of "MCM_MODEL" , you have to put your datafield
Me.PlaceHolder1.Controls.Add(dynamicRadioButton) ' Finally i added the created control to place holder
Dim MyLiteral1 = New LiteralControl 'Here I added a dynamic break after the label control
MyLiteral1.Text = "
"
Me.PlaceHolder1.Controls.Add(MyLiteral1) ' Finally i added the created control to place holder
Dim dynamicRadioButton2 As New RadioButton ' Here I am creating dynamic Radio button to show data from datatable
dynamicRadioButton2.ID = "RadioButton2_" + i.ToString()
dynamicRadioButton2.Text = dr("MCM_NAME").ToString.Trim ' Here instead of "MCM_NAME" , you have to put your datafield
Me.PlaceHolder1.Controls.Add(dynamicRadioButton2) ' Finally i added the created control to place holder
Dim MyLiteral = New LiteralControl 'Here I added a dynamic break after the label control
MyLiteral.Text = "
"
Me.PlaceHolder1.Controls.Add(MyLiteral) ' Finally i added the created control to place holder
i = i + 1 ' This is the real ONE, who is playing around.. hi hi, nothing but the count
Next
End If
End Sub
4.Thats all, now you have to call your method inside pageload as below
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.AddControl() ' Calling our method
End Sub
Hope this will help all.And let me know if theres any difficulty
Regards,
Vins