Hi muhammad12,
Check this example. Now please take its reference and correct your code.
Database
CREATE TABLE [Event]
(
ID INT,
EventName VARCHAR(50),
Property VARCHAR(50)
)
INSERT INTO [Event] VALUES (1, 'Name', 'TextBox')
INSERT INTO [Event] VALUES (2, 'Security', 'Button')
INSERT INTO [Event] VALUES (3, 'Class', 'TextBox')
INSERT INTO [Event] VALUES (4, 'Cleaning', 'Button')
HTML
<asp:Panel runat="server" ID="pnlDynamic"></asp:Panel>
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = @"SELECT * FROM [Event]";
query += "ORDER BY ";
query += "CASE WHEN Property = 'TextBox' THEN 0 ";
query += " WHEN Property = 'Button' THEN 1 ";
query += "END";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
string type = dr["Property"].ToString().ToUpper();
string eventName = dr["EventName"].ToString();
switch (type)
{
case "TEXTBOX":
Label lbl = new Label();
lbl.Text = eventName + ": ";
pnlDynamic.Controls.Add(lbl);
TextBox txt = new TextBox();
txt.ID = ID;
txt.AutoPostBack = true;
pnlDynamic.Controls.Add(txt);
Literal lt = new Literal();
lt.Text = "<br /><br />";
pnlDynamic.Controls.Add(lt);
break;
case "BUTTON":
Button btn = new Button();
btn.ID = "btn" + eventName;
btn.Text = eventName;
pnlDynamic.Controls.Add(btn);
break;
default:
break;
}
}
}
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim query As String = "SELECT * FROM [Event]"
query += "ORDER BY "
query += "CASE WHEN Property = 'TextBox' THEN 0 "
query += " WHEN Property = 'Button' THEN 1 "
query += "END"
Using con As SqlConnection = New SqlConnection(conString)
Using cmd As SqlCommand = New SqlCommand(query, con)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
For Each dr As DataRow In dt.Rows
Dim type As String = dr("Property").ToString().ToUpper()
Dim eventName As String = dr("EventName").ToString()
Select Case type
Case "TEXTBOX"
Dim lbl As Label = New Label()
lbl.Text = eventName & ": "
pnlDynamic.Controls.Add(lbl)
Dim txt As TextBox = New TextBox()
txt.ID = ID
txt.AutoPostBack = True
pnlDynamic.Controls.Add(txt)
Dim lt As Literal = New Literal()
lt.Text = "<br /><br />"
pnlDynamic.Controls.Add(lt)
Case "BUTTON"
Dim btn As Button = New Button()
btn.ID = "btn" & eventName
btn.Text = eventName
pnlDynamic.Controls.Add(btn)
Case Else
End Select
Next
End Using
End Using
End Using
End Using
End Sub
Screenshot