手动创建DataTable并绑定gridview
原文发布时间为:2008-08-04 —— 来源于本人的百度文章 [由搬家工具导入]
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;
public partial class dataset_datatable : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = new DataSet("ds_dry");//创建一个名为ds_dry的DataSet
DataTable dt = new DataTable("dt_dry");//创建一个名为dt_dry的DataTalbe
dt.Columns.Add(new DataColumn("id",typeof(int)));//为dt_dry表内建立Column
dt.Columns.Add(new DataColumn("name", typeof(string)));
dt.Columns.Add(new DataColumn("img",typeof(string)));
dt.Columns.Add(new DataColumn("timer", typeof(DateTime)));
DataRow dr = dt.NewRow();//注意这边创建dt的新行的方法。指定类型是DataRow而不是TableRow,然后不用new直接的用创建的DataTable下面的NewRow方法。
dr["id"] = 1;
dr["name"] = "AA";
dr["img"] = "~/img/1.png";
dr["timer"] = DateTime.Now;
dt.Rows.Add(dr);
dr =dt.NewRow();
dr["id"] = 2;
dr["name"] = "bb";
dr["img"] = "~/img/2.png";
dr["timer"] = DateTime.Now;
dt.Rows.Add(dr);
dr =dt.NewRow();
dr["id"] = 3;
dr["name"] = "cc";
dr["img"] = "~/img/3.png";
dr["timer"] = DateTime.Now;
dt.Rows.Add(dr);
dr =dt.NewRow();
dr["id"] = 4;
dr["name"] = "<b>dd</b>";
dr["img"] = "~/img/4.png";
dr["timer"] = DateTime.Now;
dt.Rows.Add(dr);
dr =dt.NewRow();
dr["id"] = 5;
dr["name"] = "ee";
dr["img"] = "~/img/5.png";
dr["timer"] = DateTime.Now;
dt.Rows.Add(dr);
ds.Tables.Add(dt);//别忘记向ds中添加table
Session["ds"] = ds;//存储在sessin里面,方便下面调用
fill();
}
}
private void fill()
{
DataSet ds = (DataSet)Session["ds"];//进行强制类型转换
dg.DataSource = ds;
dg.DataBind();
}
}