【问题标题】:ASP.NET C# Generate Table Dynamically doesn't workASP.NET C# 动态生成表不起作用
【发布时间】:2011-11-29 09:04:32
【问题描述】:

我一直在尝试生成一个包含 n 行的表。习惯了 PHP 让这一切变得更糟。我尝试了以下代码:

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);

但没有显示。知道为什么吗? 我只需要显示一个包含 3 列和 n 行的表格。这个行数将取决于数据库中满足特定条件的记录数。

我也试过这个:

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);

但它没有工作!

【问题讨论】:

  • 你没有说你是如何尝试使用 dTbl,或者在你的第二个例子中发生了什么。
  • 这段代码放在哪个页面的事件处理程序中?

标签: c# asp.net html-table


【解决方案1】:

而不是做“this.Controls.Add(table1)”将表格添加到.aspx页面,然后通过代码修改。

更好 - 使用数据绑定的 GridView。

【讨论】:

  • 感谢您的提示...会尝试但我相信就是这样 :)
猜你喜欢
  • 2018-05-13
  • 1970-01-01
  • 1970-01-01
  • 2014-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-25
  • 1970-01-01
相关资源
最近更新 更多