復制代碼 代碼如下:
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;
}
}