Click here to Skip to main content
15,881,852 members
Articles / Programming Languages / C#

Dynamic ASP.NET control creation using C#

Rate me:
Please Sign up or sign in to vote.
2.64/5 (10 votes)
2 Oct 2007CPOL1 min read 71.7K   856   18   4
This article explains dynamic ASP.NET control creation using C#.

Screenshot - Dynamic_Creation.jpg

Introduction

This article will teach you how to create ASP.NET Server controls dynamically and place the controls in an HTML Table which is also created dynamically according to your needs.

Using the code

Step 1

Create a new web project and create a new ASPX page. Then create an HTML table in the window and name it "myNewTable".

Important: Don't forget to make the table a server control and set visible = false. Because we are going to show the table and the rows and columns dynamically with the control.

Step 2

In the code-behind, I have a method LoadControls() which returns a DataTable. I am using the Layer concept here and use Oracle as the backend. You can do this without the Layer concept, and you can use SQL Server instead of Oracle. Create the necessary database connection for your application, and make sure that you have created the table for this sample. My sample table structure follows:

SQL
CREATE TABLE TBL_FIELD_CREATION 
( 
    FIELD_ID NUMBER(15,0) NOT NULL, 
    FIELD_NAME VARCHAR2(100) NULL, // Name for the Control 
    FIELD_LABEL VARCHAR2(100) NOT NULL, // To Display the Name 
    FIELD_TYPE VARCHAR2(100) NOT NULL, // Type of the Control like TextBox,DropDown... 
    STATUS CHAR(1) NOT NULL, // Active or Inactive to Show the control at runtime. 
    PRIMARY KEY(FIELD_ID) 
)

Insert some values into the table for textboxes and dropdown list boxes. Then select the values from the table by writing an inline SQL query or Stored Procedure based on your needs:

C#
//
// Method 1
//========
//This load control method is a method will return the datatable.
public DataTable LoadControls()
{
    try
    {
        objDt.Clear();
        objDt= objMyDl.GetDtValues("T", 0);
        // Replace your Query or Method which
        // you have written to return the values.
    }
    catch (CustomException ObjExpCust)
    {
        MsgBox(ObjExpCust.CustomErrorMessage);
    }
    catch (Exception)
    {
        MsgBox("Critical error occured. Unable to process.");
    }
    return objTrBillandCost;
}

Step 3

Create an object for HtmlTableRow and HtmlTableCell. Use different HtmlTableCell objects for different columns or cells in the HtmlTableRow. You can now assign the Style, Color, Width, and Height properties for the table, rows, and the cells.

C#
//
//Expand code snippet
//Method 2
//=========
//override protected void OnInit(EventArgs e)
{
    DataTable objDt = LoadControls();
    int row,numrows,numcells,k,l;
    row=0;
    numcells = 4;
    
    if (objDt.Rows.Count > 0)
    {
        
        myNewTable.Border = 0;
        myNewTable.Align = "center";
        
        numrows = objDt.Rows.Count;
        for (k = 1; k <= numrows; k++)
        {
            
                HtmlTableRow objRow = new HtmlTableRow();
                row = row + 1;
                for (l = 1; l <= numcells; l++)
                {
                    if (l == 1)
                    {
                        HtmlTableCell objCell1 = new HtmlTableCell();
                        objCell1.Align = "right";
                        objCell1.RowSpan = 1;
                        objCell1.ColSpan = 1;
                        objCell1.Width = "100";
                        objCell1.Height = "20";
                        Label lbl = new Label();
                        lbl.ID = "Label" + k.ToString();
                        lbl.CssClass = "LabelLeftSide";
                        lbl.Text = objDt.Rows[k - 1]["FIELD_LABEL"].ToString().Trim()+" :" ;

                        objCell1.Controls.Add(lbl);
                        objRow.Cells.Add(objCell1);
                    }
                    if (l == 2)
                    {
                        HtmlTableCell objCell2 = new HtmlTableCell();
                        objCell2.Align = "left";
                        objCell2.RowSpan = 1;
                        objCell2.ColSpan = 1;
                        objCell2.Width = "15";
                        objCell2.Height = "20";
                        objRow.Cells.Add(objCell2);
                    }
                    if (l == 3)
                    {
                        HtmlTableCell objCell3 = new HtmlTableCell();
                        objCell3.RowSpan = 1;
                        objCell3.ColSpan = 1;
                        objCell3.Width = "165";
                        objCell3.Height = "20";
                        string strControlType = 
                               objDt.Rows[k - 1]["FIELD_TYPE"].ToString().Trim();
                        if (strControlType == "D")
                        {
                            DropDownList ddltype = new DropDownList();
                            ddltype.ID = "DropDownList" + k.ToString();
                            ddltype.Style["Width"] = "165px";
                            if (ddltype.ID == "DropDownList1")
                            {
                                ddltype.Items.Add(new ListItem("--Select one--", "-1"));
                                ddltype.Items.Add("One");
                                ddltype.Items.Add("Two");
                                ddltype.Items.Add("Three");
                            }
                            else if (ddltype.ID == "DropDownList2")
                            {
                                ddltype.Items.Add(new ListItem("--Select one--", "-1"));
                                ddltype.Items.Add("Center");
                                ddltype.Items.Add("Division");
                                ddltype.Items.Add("Group");
                               
                            }
                            else
                            {
                                ddltype.Items.Add(new ListItem("--Select one--", "-1"));
                                ddltype.Items.Add("Redr");
                                ddltype.Items.Add("Blue");
                                ddltype.Items.Add("Green");
                            }
                            
                            objCell3.Controls.Add(ddltype);
                            objRow.Cells.Add(objCell3);
                        }
                        if (strControlType == "T")
                        {

                            TextBox txt = new TextBox();
                            txt.ID = "TextBox" + k.ToString();
                            txt.Style["Width"] = "165px";
                            txt.Text = "TextBox" + k.ToString();
                            txt.PreRender += new System.EventHandler(this.txt_PreRender);
                            objCell3.Controls.Add(txt);
                            objRow.Cells.Add(objCell3);
                        }
                    }
                    if (l == 4)
                    {
                        HtmlTableCell objCell4 = new HtmlTableCell();
                        objCell4.Align = "left";
                        objCell4.RowSpan = 1;
                        objCell4.ColSpan = 1;
                        objCell4.Width = "10";
                        objCell4.Height = "20";
                        objRow.Cells.Add(objCell4);
                    }
                    myNewTable.Rows.Add(objRow);
                    myNewTable.Visible = true;
                }
            }
        }
        base.OnInit(e);
    }

    //
    //
    //Reset the dropdown to default selected value.
    protected void btnReset_Click(object sender, ImageClickEventArgs e)
    {
        DropDownList ddl = new DropDownList();
        ddl = (DropDownList)this.Master.FindControl("Content").FindControl(
                     "myNewTable").FindControl("DropDownList1");
        ddl.SelectedValue = "-1";
        ddl = (DropDownList)this.Master.FindControl("Content").FindControl(
                     "myNewTable").FindControl("DropDownList2");
        ddl.SelectedValue = "-1";
        ddl = (DropDownList)this.Master.FindControl("Content").FindControl(
                     "myNewTable").FindControl("DropDownList5");
        ddl.SelectedValue = "-1";
    }

That's all!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
I'm Ganesan.S,
Software Engineer
Involved in developing MS applications for last 7 Yrs in VB,VB.NET,ASP.NET,Java Script and C#.NET lately into EPiServer and Ajax.

Comments and Discussions

 
GeneralMy vote of 5 Pin
dhinamit31-Jul-13 21:25
dhinamit31-Jul-13 21:25 
GeneralAlso Pin
Matthew Hazlett2-Oct-07 9:39
Matthew Hazlett2-Oct-07 9:39 
Instead of:
ddl = (DropDownList)this.Master.FindControl("Content").FindControl("myNewTable").FindControl("DropDownList5");
ddl.SelectedValue = "-1";

When you create a control you can add it to a hash table, like so:

Hashtable myHash = new Hashtable();
myHash.Add("Label1", new Label());
myHash.Add("DropDown1", new DropDown());

Label thisLabel = myHash["Label1"] as Label;
DropDownList thisDropDown = myHash["DropDown1"] as DropDownList;

This way you don't have to worry about findcontrol (a very ugly function).
Or because you only have 3 and not a dynamic amount you could just assign them to variables, Just a thought.




Matthew Hazlett

Sometimes I miss the simpler DOS days of Borland Turbo Pascal (but not very often).

GeneralRe: Also Pin
Ganesan Sankaran2-Oct-07 18:10
Ganesan Sankaran2-Oct-07 18:10 
GeneralVery messy, try this Pin
Matthew Hazlett2-Oct-07 9:15
Matthew Hazlett2-Oct-07 9:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.