ASP.Net C# Code to Create Dynamic Tables

by top54u.com 06 Mar, 2008

In ASP.Net 2.0 there are number of controls to display the data retrieved from the database in tabular form using Grid View Control, list view Control, Repeater. But in some cases when there is no option to custom these default controls. At that time a questions arises – how to generate dynamic tables? How to display the data according to requirement?

You can use the Literal Control to display the html tagged string generated by using VB/C# code in ASP.Net 2.0.

(Advance ASP.Net developers: See Alternate Example here using Panel Control to Create dynamic tables using HtmlControls HtmlTable)

 

To generate the table using string variables you can use the following C# code:

 

// create a string type variable to generate dynamic table

string dynTable="";

 

// start with table tag with following attributes

dynTable = "<table cellspacing=\"0\" cellpadding=\"2\" border=\"1\">";

 

// outer loop to generate table rows

for (int tRows = 0; tRows < 5; tRows++)

{

 

//start table row

dynTable += "<tr>";

 

// inner loop to generate columns

for (int tCols = 0; tCols < 4; tCols++)

{

// create column

dynTable += "<td>"; dynTable += "Row: " + (tRows+1) + " Col: " + (tCols+1) ;

// close td column tag

dynTable += "</td>";

}

 

// close table row

dynTable += "</tr>";

}

 

// close the table tag

dynTable += "</table>";

Literal1.Text = dynTable;

 

Above C# code will build a string having table tag, tr as table row, td as table data/column. To display the data retrieved from database you can set the tRows < [No. of DataRows Retrieved] and tCols < [No. of DataColmns].

Output Result of above code:

 

Row: 1 Col: 1 Row: 1 Col: 2 Row: 1 Col: 3 Row: 1 Col: 4
Row: 2 Col: 1 Row: 2 Col: 2 Row: 2 Col: 3 Row: 2 Col: 4
Row: 3 Col: 1 Row: 3 Col: 2 Row: 3 Col: 3 Row: 3 Col: 4
Row: 4 Col: 1 Row: 4 Col: 2 Row: 4 Col: 3 Row: 4 Col: 4
Row: 5 Col: 1 Row: 5 Col: 2 Row: 5 Col: 3 Row: 5 Col: 4

 

Learn Also:

ASP.Net C# Database Connection

ASP.Net Connect to SQL Database

Spotlight.....

Currently rated 2.7 by 3 people

  • Currently 2.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , ,

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

10/11/2008 3:28:29 AM




related videos.....
recent posts.....
top54u ezines.....