Create Dynamic Tables in ASP.NET

In ASP.Net 2.0, several controls 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 question arises – how to generate dynamic tables? How to display the data according to requirement?

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

To generate the table, you can use the following C# code:

 private static string GenerateTable()
        {
            // 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>";
            return dynTable;
        }

How to use

Literal1.Text = GenerateTable(); 

Above C# code will build a string having table tag, tr as a table row, td as table data/column. To display the data retrieved from the 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

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru