//添加新行
DataRow newRow = dt.NewRow();
dt.Rows.Add(newRow);
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text;
public partial class CreateDataTable : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ReadData();
}
private void ReadData()
{ ///创建数据库链接
string conString = ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRING"].ConnectionString;
SqlConnection myCon = new SqlConnection(conString);
///创建执行命令
SqlCommand myCmd = new SqlCommand("SELECT TOP 5 * FROM Catalog ORDER BY ID DESC",myCon);
///定义dr
SqlDataReader dr = null;
try
{ ///打开数据库的链接
myCon.Open();
///从数据库读取数据
dr = myCmd.ExecuteReader();
///创建DataTabel,并显示DataTable中的数据
ShowData(CreateDataTableData(dr));
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{ ///关闭数据库的链接
myCon.Close();
}
}
private DataTable CreateDataTableData(SqlDataReader dr)
{
DataTable dt = new DataTable();
///创dt的列
foreach(DataRow row in dr.GetSchemaTable().Rows)
{ ///需要列的名称和数据类型
dt.Columns.Add(new DataColumn(row["ColumnName"].ToString(),(Type)row["DataType"]));
}
///读取数据
while(dr.Read())
{ ///创建一个新行
DataRow newrow = dt.NewRow();
foreach(DataRow row in dr.GetSchemaTable().Rows)
{ ///读取数据
newrow[row["ColumnName"].ToString()] = dr[row["ColumnName"].ToString()];
}
///添加新行
dt.Rows.Add(newrow);
}
///关闭读取器
dr.Close();
return (dt);
}
private void ShowData(DataTable dt)
{
StringBuilder sb = new StringBuilder();
///添加表头
sb.Append("<table border=1>");
///添加表的标题栏
sb.Append("<tr>");
for(int i = 0; i < dt.Columns.Count; i++)
{
sb.Append("<td bgcolor=gray>");
sb.Append(dt.Columns[i].ColumnName);
sb.Append("</td>");
}
sb.Append("</tr>");
///添加数据
foreach(DataRow row in dt.Rows)
{ ///添加一行数据
sb.Append("<tr>");
for(int i = 0; i < row.ItemArray.Length; i++)
{ ///添加数据的列
sb.Append("<td>");
sb.Append(row.ItemArray[i].ToString());
sb.Append("</td>");
}
sb.Append("</tr>");
}
///添加结束符号
sb.Append("</table");
sb.Append("<hr />");
///输出字符串
Response.Write(sb.ToString());
}
}