Tuesday, February 5, 2008

Creating dynamic tables and text boxes inside using .NET with C#


I recently saw a post requesting help to create text boxes dynamically using C#. Besides the dynamic text boxes the requester needed another funcationality that these text boxes should be in a table. That is, each text box in a seperate cell. I left the post at that time and couldn't find where the question is.



Well, we can do that. How? To accomplish this task we have to know about the following properties.
1. The Controls collection of Control class.
2. The Add method of collections
3. The LiteralControl class.

The LiteralControl class allows us to create html tags that we normally put in the html view of the aspx page. It is almost similar to write the html tags directly to the page using Response.Write(). However we can't control the position of these html tags easily. LiteralControl can be treated as of any other web control and can be added to any of the container classes like Panel, PlaceHolder etc.

Ok, here we are going to use Panel, LiteralControl and TextBox server controls and generate the text boxes dynamically by taking a list.

Here is the code:

Create a web project in Visual Studio using C#. A web form will be added to the project by default (what ever the version of the Visual Studio be).

Drop a Panel on top of the web page. This is our container. Just give the name container. Switch to the code view.

First let us write a small function that determines the items in the dynamic list.
// This method can be anything that returns a string array
// Can be read from a configuration file or from database

private string[] GetItems()
{
string items = "Item1,Item2,Item3,Item1,Item2";
return items.Split(',');
}

Now we have to write the method that does the actual work

private string[] CreateDynamicControls() 
{
Container.Controls.Add(new LiteralControl("<TABLE border=1>"));
Container.Controls.Add(new LiteralControl("<TR>"));
string[] parameters = GetItems
foreach(string parameter in parameters)
{
Container.Controls.Add(new LiteralControl("<TD width=150px>"));
Label label = new Label();
label.ID = string.Format("{0}Label", parameter);
label.Text = string.Format("{0}: ", parameter);
Container.Controls.Add(label);
TextBox editBox = new TextBox();
editBox.ID = parameter;
Container.Controls.Add(editBox);
Container.Controls.Add(new LiteralControl("</TD>"));
}
Container.Controls.Add(new LiteralControl("</TR>"));
Container.Controls.Add(new LiteralControl("</TABLE>"));
}

Now we have to call this method from any of the Page events. The better place is OnInit, though we can successfully call this method from PageLoad.