asp.net 动态生成表格
程序员文章站
2024-03-09 17:01:35
复制代码 代码如下:using system; using system.collections.generic; using system.linq; using sys...
复制代码 代码如下:
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;
using system.data;
using system.text;
public partial class default2 : system.web.ui.page
{
// 步骤
// 1. 要有个总的方法来拼字符串 好比是 private string makestring()
// 2. 在这个总的方法里面要有个来获取数据的方法 好比是 private datatable fetchdata()
protected void page_load(object sender, eventargs e)
{
response.write(makestring());
}
/* 这个是拼装字符串的方法 */
private string makestring()
{
datatable dtdata = fetchdata();
stringbuilder strcontent = new stringbuilder();
string strformate = "<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>";
strcontent.append("<table>");
foreach(datarow row in dtdata.rows)
{
strcontent.appendformat(strformate, row[0].tostring(), row[1].tostring(), row[2].tostring());
}
strcontent.append("</table>");
return strcontent.tostring();
}
private datatable fetchdata()
{
// 这里是拼装,你也可以自己获得
datatable dtdata = new datatable();
dtdata.columns.add("c1");
dtdata.columns.add("c2");
dtdata.columns.add("c3");
dtdata.rows.add(new string[] { "1-1", "1-2", "1-3" });
dtdata.rows.add(new string[] { "2-1", "2-2", "2-3" });
dtdata.rows.add(new string[] { "3-1", "3-2", "3-3" });
dtdata.rows.add(new string[] { "4-1", "4-2", "4-3" });
dtdata.rows.add(new string[] { "5-1", "5-2", "5-3" });
return dtdata;
}
}