Dynamically create controls in C# (ASPX/Web) from database record and fetch control data

1.7k Views Asked by At

Folks,

Need one help in creating the dynamic controls in C#. Like, I am putting ID, Text and all the mandatory validation properties into the database and from that values I need to create a control in ASP WinForm or Web page.

Please suggest me the view part to achieve the same.

here is my database table template

CREATE TABLE CONTROL(
    PK_CONTROL_ID VARCHAR(128) NOT NULL,
    CONTROL_NAME VARCHAR(128) NOT NULL,
    PRIMARY KEY(CONTROL_ID)
);


CREATE TABLE CONTROLPROPERTY(
    PK_PROPERTY_ID INT NOT NULL IDENTITY(1,1),
    FK_CONTROL_ID INT NOT NULL FOREIGN KEY REFERENCES CONTROLPROPERTY(PK_CONTROL_ID),
    CONTROLPROPERTY VARCHAR(128) NOT NULL,
    CONTROLVALUES VARCHAR(128) NOT NULL,
    PRIMARY KEY(PK_PROP_VALUE_ID)
);


**Example**
PK_CONTROL_ID  CONTROL_NAME
1               TextBox


PK_PROPERTY_ID  FK_CONTROL_ID  CONTROLPROPERTY  CONTROLVALUES
1               1               ID              txtName
2               1               Visible         true
3               1               ToolTip         Name

Refered this example but I need to implement same table structure for the different types of controllers

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="TestControlFirst.index" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load (object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("Firstname");
        dt.Columns.Add("Lastname");
        for (int i = 0; i < 10; i++)
        {
             DataRow row = dt.NewRow();
            row.ItemArray = new object[] {i,"Joe_"+i.ToString(),"Blow" +i.ToString()};
             dt.Rows.Add(row);
            Repeater1.DataSource = dt;
            Repeater1.DataBind();
        }
     }
}

protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    int rowid = (e.Item.ItemIndex);
    TextBox tb = (TextBox)Repeater1.Items[rowid].FindControl("txtOne");
    Label2.Text = tb.Text;
}
</script>

ASPX page

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Repeater Demo</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
<asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand">
<HeaderTemplate>
<table border="1" width="50%">
<tr>
<th>SELECT</th>
<th>ID</th>
<th>FIRST</th>
<th>LAST</th>  
</tr>
</HeaderTemplate>

<ItemTemplate>
<tr>
  <td><asp:Button ID="btnOne" runat="server" Text="SELECT"   /></td>
  <td> <asp:TextBox ID="txtOne" runat="server" Text='<%# Eval("ID") %>' /></td>
<td><%# Eval("Firstname") %></td>
<td><%# Eval("LastName") %></td>

</tr>
</ItemTemplate>

<FooterTemplate>
</table>
</FooterTemplate>
        </asp:Repeater>
    </div>
    <asp:Label ID="Label2" runat="server"></asp:Label>
    </form>
</body>
</html>

Thanks in advance

1

There are 1 best solutions below

0
On

Your best bet is to create dynamic Controls and add them to a PlaceHolder by looping the database rows and create Controls based on the row values. This needs to happen every time the page is loaded, and that includes a PostBack

while (reader.Read())
{
    string controlType = reader["CONTROL_NAME"].ToString();

    if (controlType == "TextBox")
    {
        TextBox textbox = new TextBox();
        textbox.ID = reader["ID"].ToString();
        textbox.Visible = Convert.ToBoolean(reader["Visible"]);
        textbox.ToolTip = reader["ToolTip"].ToString();
        PlaceHolder1.Controls.Add(textbox);
    }
    else if (controlType == "Label")
    {
        Label label = new Label();
        label.ID = reader["ID"].ToString();
        label.Visible = Convert.ToBoolean(reader["Visible"]);
        label.Text = reader["Text"].ToString();
        PlaceHolder1.Controls.Add(label);
    }
    else if (controlType == "Button")
    {
        //etc
    }
}

And to read the form values on submit you basically need to do the same. Loop all the ID's and Control types from the database, create them dynamically and read their values.

As you can see this process can become complex real fast if you have a lot of different controls and rows, so think about your approach and see if this is the best solution.