前:
<%@ 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="1" width="400"> <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;//列的起值为1 dc1.AutoIncrementStep = 1;//步长为1 data.Columns.Add(dc1);//添加到表中 //创建一个新UserName ,string类型的列 DataColumn dc = new DataColumn("UserName", typeof(string)); dc.Unique = true;//设置唯一索引 dc.MaxLength = 20; data.Columns.Add(dc); dc = new DataColumn("Birthday", typeof(DateTime)); dc.DefaultValue = DateTime.Now.AddYears(-2000); data.Columns.Add(dc); DataRow row =data.NewRow();//得到与刚才创建的表具有相同结构的行 row["UserName"] = "李四"; data.Rows.Add(row);//添加行 row = data.NewRow(); row["UserName"] = "王五"; row["Birthday"] = new DateTime(1, 3, 4); data.Rows.Add(row); row = data.NewRow(); row["UserName"] = "赵五"; row["Birthday"] = new DateTime(6, 7, 11); data.Rows.Add(row); Session["Data"] = data; } protected void ShowData() { if (Session["Data"] == null) { CreateDataTable(); } DataTable data = (DataTable)Session["data"]; for (int i = 0; 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>"); } } } }
图片显示: