0

I've been trying to generate a table with n number of rows. Being used to PHP makes this all the worst. I tried the following code:

using System.Data;

// Create a DataTable instance
DataTable dTbl = new DataTable("myDynamicTable");

// Create a DataColumn instances

DataColumn dValue = new DataColumn();
DataColumn dMember = new DataColumn();

dValue.ColumnName = "Id";
dValue.DataType = Type.GetType("System.Int32");

dMember.ColumnName = "Name";
dMember.DataType = Type.GetType("System.String");

// Add these DataColumns into the DataTable

dTbl.Columns.Add(dValue);

dTbl.Columns.Add(dMember);
DataRow myrow = dTbl.NewRow();

myrow["Id"] = 1;
myrow["Name"] = "Tux";

// Add the row into the table

dTbl.Rows.Add(myrow);

but nothing displayed. Any idea why? All I need is to display a table with 3 columns and n number of rows. This number will of rows will be dependent on number of records in database satisfying a certain conditions.

I also tried this:

HtmlTable table1 = new HtmlTable();

// Set the table's formatting-related properties.
table1.Border = 1;
table1.CellPadding = 3;
table1.CellSpacing = 3;
table1.BorderColor = "red";

// Start adding content to the table.
HtmlTableRow row;
HtmlTableCell cell;
for (int i = 1; i <= 5; i++)
{
    // Create a new row and set its background color.
    row = new HtmlTableRow();
    row.BgColor = (i % 2 == 0 ? "lightyellow" : "lightcyan");

    for (int j = 1; j <= 4; j++)
    {
        // Create a cell and set its text.
        cell = new HtmlTableCell();
        cell.InnerHtml = "Row: " + i.ToString() +
          "<br>Cell: " + j.ToString();

        // Add the cell to the current row.
        row.Cells.Add(cell);
    }

    // Add the row to the table.
    table1.Rows.Add(row);
}

// Add the table to the page.
this.Controls.Add(table1);

but it didn't work!

2
  • You haven't said anything about how you were trying to use dTbl, or what happened in your second example. Commented Oct 2, 2011 at 11:49
  • Which page's event handler this code placed in? Commented Oct 2, 2011 at 12:33

1 Answer 1

1

Instead of doing "this.Controls.Add(table1)" add the table to the .aspx page, and then modify it through the code.

Even better - use a databound GridView.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the hint...will try it out but I believe this is it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.