Click here to Skip to main content
6,595,444 members and growing! (19,895 online)
Email Password   helpLost your password?
Desktop Development » Miscellaneous » General     Intermediate

Dynamic ASP.Net Control Creation Using C#.Net

By Ganesan Sankaran

Dynamic ASP.Net Control Creation Using C#.Net .
C# 2.0, Windows, .NET 2.0VS2005, Dev
Posted:2 Oct 2007
Views:32,682
Bookmarked:16 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
8 votes for this article.
Popularity: 2.13 Rating: 2.36 out of 5
3 votes, 37.5%
1
1 vote, 12.5%
2
2 votes, 25.0%
3
1 vote, 12.5%
4
1 vote, 12.5%
5
Screenshot - Dynamic_Creation.jpg

Introduction

This artical will teach you how to create the ASP.Net Server controls dynamically and place the controls into the HTML Table which is also created dynamically according to your need.

Landuage

C#.Net

Using the code

Create the ASP.NET Controls and Place it into HTML Tables Dynamically using C#.Net

Step 1

Create a new web project and create a new aspx page ,then create the one html table in the html design as follows

here above i have created the html table in the html design section and i given the name for the table as "myNewTable"

Important : Don't forget make the table as server control and give the visible = false.why because we are going to show the table and the rows and column dynamcally with control

Step 2

Come to the code behind ,I have method called LoadControls() which return the DataTable.Here i used the Layer concept and am using the Orcale as Backend. You can do this without layer concept and you can use SQL instead of Oracle. Make the necessary Database connection for your application before that make sure that you have created the table for this one or not. My sample table structure as follows.

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 Dropdownlist boxes.Then Select the Values from the table by writting Inline SQL Query or Stored Procedure according to your need.

//
// 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 column or cell in the HtmlTableRow. You can assign the Style,Color width and height properties for Table,Rows and as well as Cells.

//
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";
    }
//

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Ganesan Sankaran


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

Other popular Miscellaneous articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 3 of 3 (Total in Forum: 3) (Refresh)FirstPrevNext
GeneralAlso PinmemberMatthew Hazlett10:39 2 Oct '07  
GeneralRe: Also PinmemberGanesan Sankaran19:10 2 Oct '07  
GeneralVery messy, try this PinmemberMatthew Hazlett10:15 2 Oct '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 2 Oct 2007
Editor:
Copyright 2007 by Ganesan Sankaran
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project