Click here to Skip to main content
16,018,904 members
Articles / Programming Languages / SQL

.NET Dynamic Control (Label, Text Box and Drop Down) Creation

Rate me:
Please Sign up or sign in to vote.
4.73/5 (10 votes)
4 Jul 2011CPOL3 min read 62.6K   2.4K   38   24
.NET Dynamic Control Creation

Table of Contents

Introduction

Before I begin the introduction with dynamic control, I just want to specify how the control works on page. I got a doubt at the very beginning as to how the control persists on the page even after postback.

Well, here you go...

Whenever we run the page, it will be posted to the server, and the new instance of web page will get created every time and this means the page and the control on the page would get lost on every round trip. This has been overcome using the viewstate in ASP.NET which is a default properly of page, when we set viewstate of page to true, the viewstate property provides a dictionary object for retaining values between multiple roundtrips for the same page. It means before the page load ends, the control will be retained on the page and after the page load, we will be able to see the controls.

What is Dynamic Control

Yep, now let’s move to the term dynamic, the control which is not on design on the aspx page which framework parses, but the one we create by making the postback of the page by firing an event of another control. For example, create a textbox on button click.

However, it's better to understand that all controls on a page are actually dynamic at some stage of the page lifecycle.

The simple thing to remember here is that when we create a control on any event and want to retain them on any other action, then we should create them at every postback of the page.

Sample of Dynamic Control

As talked about earlier, we can create a control on any event. Here, we will use a listbox and on its SelectedIndexChanged, we will create a control.

Before we go far ahead, let’s see the DB design so that it will be clear as to what and how we move.

Please download and restore the DB in SQL Server.

Steps to restore can be found at this link.

Now, let me elaborate more. On Page load, I populate listbox. I am bind the MASTERDATATABLELIST table to Listbox where the DataTextField of the listbox is Table description (TABLENAMEDESC) and the Datavalue field is FILTERQUERY. (This field contains the SQL query select statement.)

Example

TABLENAMEDESCFILTERQUERY
ROLESSELECT Role "Role Description" , RoleID "Role Code" FROM AllRoles
C#
public void BindListControl()
{
       string connectionStr = System.Configuration.ConfigurationManager.ConnectionStrings
				["ConnectionString"].ToString();
        SqlHelpe dataaccessHelper = new SqlHelpe(connectionStr);
         DataSet dataSet = new DataSet();
         string Mainquery = ViewState["MainQuery"].ToString();
        // View state is used here as per my requirement but recommended to avoid here
         dataSet = dataaccessHelper.ExecuteSelectQuery(Mainquery);
         lstTables.DataSource = dataSet.Tables[0];
         lstTables.DataTextField = "TABLENAMEDESC";
         lstTables.DataValueField = "FILTERQUERY";
         lstTables.DataBind();
}

Now let’s look at the dynamic control creation. We will be creating the control based on the fields in the select query and it will get changed as the query gets changed on selection. We will use the same control fields as filter parameters to retrieve the data.

Screen Design

Image 1

Now let’s consider the select query on SelectedIndexChanged of listbox data “COUNTRY”.

Image 2

As per the query, the place holder will be with the data table and each cell of the data table will contain Label and Textbox.

Image 3

The code for creating dynamic textbox and label is as follows:

C#
double rCount = Math.Ceiling(((double)columnCount / 4));
                int k = 0, rowsCount;
                rowsCount = (int)rCount;
                Table table = new Table();
                table.ID = "Table1";

                PlaceHolder1.Controls.Add(table);
                for (int i = 0; i < rowsCount; i++)
                {
                    int kC = 0;
                    TableRow row = new TableRow();
                    for (int j = 0; j < 4; j++)
                    {
                        TableCell cell = new TableCell();
                        Label lbl = new Label();
                        lbl.CssClass = "captions";
                        lbl.Width = 130;
                        lbl.ID = "Lable_" + i + "Col_" + j;
                        lbl.Text = StringArry[k, kC + 1].ToString();
                        TextBox tb = new TextBox();
                        tb.ID = StringArry[k, kC];
                        tb.Attributes.Add("EventHandler", "TextChanged");
                        // Add the control to the TableCell
                        cell.Controls.Add(lbl);
                        cell.Controls.Add(tb);
                        // Add the TableCell to the TableRow
                        row.Cells.Add(cell);
                        k = k + 1;
                        if (i * 4 + j == (columnCount - 1))
                        {
                            break;
                        }
                    }
                    // Add the TableRow to the Table
                    table.Rows.Add(row);
                }
            }

But now the question is, what if the query contains many fields in it. Well, we can show but we will lose the beauty in the page. I even want to cover how to bind dropdown on the page.

So here, if the query contains more than 8 fields, then we will see dropdown instead of textbox. So we will show for the below query:

Image 4

Image 5

Now, we will use the control(s) to add parameter and pass into where condition to get data on load button click (see below):

Image 6

The code for dynamic dropdown creation is as follows:

C#
double rCount = 2; Math.Ceiling(((double)columnCount / 3));
int k = 0, rowsCount;
rowsCount = (int)rCount;
Table table = new Table();
table.ID = "Table1";

PlaceHolder1.Controls.Add(table);

for (int i = 0; i < rowsCount; i++)
{
    int kC = 0;
    TableRow row = new TableRow();
    for (int j = 0; j < 3; j++)
    {
        TableCell cell = new TableCell();
        Label lbl = new Label();
        lbl.Width = 25;
 
        lbl.Text = "  ";
        DropDownList ddlist = new DropDownList();
        ddlist.Attributes.Add("EventHandler", "SelectedIndexChanged");
        ddlist.CssClass = "DropDownText";
        ddlist.ID = "ddl_" + k;
        ddlist.DataSource = dtStringArry;
        ddlist.DataTextField = dtStringArry.Columns["Col2"].ToString();
        ddlist.DataValueField = dtStringArry.Columns["Col1"].ToString();
        ddlist.DataBind();
        ddlist.Items.Insert(0, new ListItem("-SELECT-", "SELECT"));
        ddlist.SelectedIndex = 0;
        TextBox tb = new TextBox();
        tb.ID = "txt_" + k;
        tb.Attributes.Add("EventHandler", "TextChanged");
        cell.Controls.Add(ddlist);
        cell.Controls.Add(lbl);
        cell.Controls.Add(tb);
        row.Cells.Add(cell);
        k = k + 1;
        if (i * 3 + j == (columnCount - 1))
        {
            break;
        }
    }
    // Add the TableRow to the Table
    table.Rows.Add(row);
}

Reading the textbox control data:

C#
TextBox tb = (TextBox)PlaceHolder1.FindControl(controlArrry[i, 0]);
 if (!String.IsNullOrEmpty(tb.Text))
 {
	string name1 = null;
	string strValue = tb.Text.ToString();
	name1 = tb.ID + " Like " + "'%" + tb.Text.Trim() + "%'" + " OR ";
	whereQuery += name1;
 }

Reading dropdown control data:

C#
DropDownList ddl = (DropDownList)PlaceHolder1.FindControl("ddl_" + i);
if (!String.IsNullOrEmpty(ddl.SelectedValue) && ddl.SelectedValue != "SELECT")
{
	TextBox tb = (TextBox)PlaceHolder1.FindControl("txt_" + i);
	if (!String.IsNullOrEmpty(tb.Text))
	{
	 string name1 = null;
	 string strValue = tb.Text.ToString();
	 name1 = ddl.SelectedValue + " Like " + "'%" + tb.Text.Trim() + "%'" + " OR ";
	 whereQuery += name1;
	}
}

History

  • 26th June, 2011: Initial version
  • 29th June, 2011: Uploaded source code
  • 2nd July, 2011: Updated images

License

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


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalgreat codes thanks Pin
Member 97537318-Feb-16 4:59
Member 97537318-Feb-16 4:59 
Questionnice Pin
BillW3331-Aug-12 3:15
professionalBillW3331-Aug-12 3:15 
AnswerRe: nice Pin
Shrilata Ellaboina13-Sep-12 7:21
Shrilata Ellaboina13-Sep-12 7:21 
GeneralRe: nice Pin
BillW3313-Sep-12 9:41
professionalBillW3313-Sep-12 9:41 
QuestionCouldn't find files in Account directory Pin
Member 823625816-Jun-12 8:30
Member 823625816-Jun-12 8:30 
AnswerRe: Couldn't find files in Account directory Pin
Shrilata Ellaboina17-Jun-12 3:27
Shrilata Ellaboina17-Jun-12 3:27 
QuestionGetting error Pin
Member 823625816-Jun-12 8:06
Member 823625816-Jun-12 8:06 
AnswerRe: Getting error Pin
Shrilata Ellaboina17-Jun-12 3:26
Shrilata Ellaboina17-Jun-12 3:26 
GeneralMy vote of 5 Pin
xExTxCx1-Jul-11 6:36
xExTxCx1-Jul-11 6:36 
SuggestionGood Job Done Pin
Mr.Sourav.Maitra30-Jun-11 7:35
Mr.Sourav.Maitra30-Jun-11 7:35 
GeneralRe: Good Job Done Pin
Shrilata Ellaboina30-Jun-11 19:05
Shrilata Ellaboina30-Jun-11 19:05 
GeneralRe: Good Job Done Pin
Shrilata Ellaboina4-Jul-11 19:20
Shrilata Ellaboina4-Jul-11 19:20 
GeneralRe: Good Job Done Pin
Mr.Sourav.Maitra9-Jul-11 6:15
Mr.Sourav.Maitra9-Jul-11 6:15 
GeneralMy vote of 5 Pin
Rajneesh Rai30-Jun-11 5:05
Rajneesh Rai30-Jun-11 5:05 
GeneralRe: My vote of 5 Pin
Shrilata Ellaboina30-Jun-11 19:04
Shrilata Ellaboina30-Jun-11 19:04 
SuggestionSee this! Pin
CS140129-Jun-11 19:27
CS140129-Jun-11 19:27 
GeneralRe: See this! Pin
Shrilata Ellaboina30-Jun-11 18:57
Shrilata Ellaboina30-Jun-11 18:57 
GeneralRe: See this! Pin
Shrilata Ellaboina4-Jul-11 19:19
Shrilata Ellaboina4-Jul-11 19:19 
GeneralRe: See this! Pin
CS14015-Jul-11 2:18
CS14015-Jul-11 2:18 
GeneralRe: See this! Pin
Shrilata Ellaboina9-Dec-11 5:45
Shrilata Ellaboina9-Dec-11 5:45 
SuggestionImprove Screenshots Pin
AspDotNetDev29-Jun-11 7:51
protectorAspDotNetDev29-Jun-11 7:51 
GeneralRe: Improve Screenshots Pin
Shrilata Ellaboina30-Jun-11 19:02
Shrilata Ellaboina30-Jun-11 19:02 
GeneralMy vote of 5 Pin
_Tushar Patil29-Jun-11 3:44
_Tushar Patil29-Jun-11 3:44 
Fabulous......I was Searching For This type of Article
GeneralRe: My vote of 5 Pin
Shrilata Ellaboina30-Jun-11 19:01
Shrilata Ellaboina30-Jun-11 19:01 

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.