当前位置:Gxlcms > asp.net > asp.net 动态生成表格

asp.net 动态生成表格

时间:2021-07-01 10:21:17 帮助过:39人阅读

代码如下:
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;
}
}

人气教程排行