手动创建DataTable对象并绑定

时间:2020-12-07 19:46:50

 

  public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                createDT();
            }
        }

        private void createDT()
        {
            using (DataTable dt = new DataTable("article"))
            {
                DataColumn dtc = new DataColumn("文章ID", typeof(Int32));
                dt.Columns.Add(dtc);                
                dtc = new DataColumn("标题", typeof(String));
                dt.Columns.Add(dtc);
                dtc = new DataColumn("作者", typeof(String));
                dt.Columns.Add(dtc);
                            
                DataRow dtr = dt.NewRow();
                dtr["文章ID"] = 1;
                dtr["标题"] = "很高兴";
                dtr["作者"] = "王一";
                dt.Rows.Add(dtr);

                DataRow dtr1 = dt.NewRow();
                dtr1["文章ID"] = 2;
                dtr1["标题"] = "太高兴了";
                dtr1["作者"] = "王二";
                dt.Rows.Add(dtr1);
               
                GridView1.DataSource = dt;
                GridView1.DataBind(); }
        }

    }