前:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataTable对象.aspx.cs" Inherits="WebApplication1.DataTable对象" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table border="" width="">
<tr><td>编号</td><td>用户名</td><td>生日</td></tr>
<% ShowData();
%>
</table>
</div>
</form>
</body>
</html>

CS代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data; namespace WebApplication1
{
public partial class DataTable对象 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void CreateDataTable()
{
//实例化DataTable
DataTable data = new DataTable();
//创建一个名为“ID”的列,值类型为int
DataColumn dc1 = new DataColumn("ID", typeof(int));
dc1.AllowDBNull = false;//不许为空
dc1.AutoIncrement = true;//自动增长
dc1.AutoIncrementSeed = ;//列的起值为1
dc1.AutoIncrementStep = ;//步长为1
data.Columns.Add(dc1);//添加到表中 //创建一个新UserName ,string类型的列
DataColumn dc = new DataColumn("UserName", typeof(string));
dc.Unique = true;//设置唯一索引
dc.MaxLength = ;
data.Columns.Add(dc); dc = new DataColumn("Birthday", typeof(DateTime));
dc.DefaultValue = DateTime.Now.AddYears(-);
data.Columns.Add(dc); DataRow row =data.NewRow();//得到与刚才创建的表具有相同结构的行
row["UserName"] = "李四";
data.Rows.Add(row);//添加行 row = data.NewRow();
row["UserName"] = "王五";
row["Birthday"] = new DateTime(, , );
data.Rows.Add(row); row = data.NewRow();
row["UserName"] = "赵五";
row["Birthday"] = new DateTime(, , );
data.Rows.Add(row); Session["Data"] = data; }
protected void ShowData()
{
if (Session["Data"] == null)
{
CreateDataTable();
}
DataTable data = (DataTable)Session["data"];
for (int i = ; i < data.Rows.Count; i++)
{
Response.Write("<tr>");
Response.Write("<td>" + data.Rows[i]["ID"].ToString() + "</td>");
Response.Write("<td>" + data.Rows[i]["UserName"].ToString() + "</td>");
Response.Write("<td>" + DateTime.Parse(data.Rows[i]["Birthday"].ToString()).ToShortDateString() + "</td>");
Response.Write("</tr>");
}
}
}
}

图片显示:DataTabe对象的例子-LMLPHP

04-19 19:33