如何为DATATABLE添加多行(转贴)

 DataColumn 是用来模拟物理数据库中的列。DataColumn 的组合组成了 DataTable 中列的架构。生成 DataTable 架构的方法就是向 DataColumnCollection 中添加DataColumn 对象来生成架构。同物理数据库一样,列是有类型的,比如 varchar, datatime, int 等, DataColumn 有 DataType 属性表示这一列所存储的数据种类。由于 DataTable 所包含的数据通常合并回其原始数据源,因此必须使其数据类型与数据源中的数据类型匹配。这个匹配关系,可以再 msdn 中的 《数据类型映射 (ADO.NET)》章节查询到。

  在物理数据库中,我们的列都要有各种约束来维持数据完整性,比如非空、唯一,同时也有各种自动化的操作,比如,自增。同样的在内存中,我们也可以这样定义,通过 AllowDBNull 、Unique 和 ReadOnly 等属性对数据的输入和更新施加限制,通过 AutoIncrement、AutoIncrementSeed 和 AutoIncrementStep 属性来实现数据自动生成。

DataTable tblDatas = new DataTable("Datas");

DataColumn dc = null;

dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));

dc.AutoIncrement = true;//自动增加

dc.AutoIncrementSeed = 1;//起始为1

dc.AutoIncrementStep = 1;//步长为1

dc.AllowDBNull = false;//

  tblDatas.Columns.Add("Product", Type.GetType("System.String"));

  tblDatas.Columns.Add("Version", Type.GetType("System.String"));

  tblDatas.Columns.Add("Description", Type.GetType("System.String"));

DataRow newRow;

newRow = tblDatas.NewRow();

newRow["Product"] = "ddf";

newRow["Version"] = "fgfg";

newRow["Description"] = "fgfg";

tblDatas.Rows.Add(newRow);

newRow = tblDatas.NewRow();

newRow["Product"] = "gffg";

newRow["Version"] = "gffg";

newRow["Description"] = "gfg";

tblDatas.Rows.Add(newRow);

posted @ 2014-05-28 10:00  雨中超越  阅读(2925)  评论(0编辑  收藏  举报