DataSet的初始化构建、定义、赋值、使用、添加(合并)
作者:互联网
自定义建表方法DataTable
public DataTable BuildDataTable(string tablename, params string[] colname) { DataTable dt = new DataTable(); dt.TableName = tablename; foreach (string col in colname) { dt.Columns.Add(col,typeof(string)); } return dt; }
DataSet的初始化构建、定义、赋值、使用
var ds = new DataSet("DataSet"); var bdt = new DataTable("DataTable1"); bdt.Columns.Add("Column1"); bdt.Columns.Add("Column2"); var cdt = new DataTable("DataTableA"); cdt.Columns.Add("ColumnA"); cdt.Columns.Add("ColumnB"); cdt.Columns.Add("ColumnC"); for (int i = 0; i < 10; i++) { DataRow bdr = bdt.NewRow(); bdr["Column1"] = "123"; bdr["Column2"] = 10; bdt.Rows.Add(bdr); DataRow cdr = cdt.NewRow(); cdr["ColumnA"] = "123"; cdr["ColumnB"] = 10; cdr["ColumnC"] = "2230"; cdt.Rows.Add(cdr); } ds.Tables.Add(bdt); ds.Tables.Add(cdt); Console.WriteLine(ds.DataSetName); if (ds.Tables.Count > 0) { for (int i = 0; i < ds.Tables.Count; i++) { //if (i == 0) // continue; if (ds.Tables[i].Columns.Count > 0) { Console.WriteLine("表名:" + ds.Tables[i].TableName); for (int j = 0; j < ds.Tables[i].Columns.Count; j++) { //if (j == 1) // break; Console.WriteLine(ds.Tables[i].Columns[j].ColumnName); } } } }
输出
DataSet 表名:DataTable1 Column1 Column2 表名:DataTableA ColumnA ColumnB ColumnC
DataSet的添加或者合并
var a =BuildDataTable("表名1", "字段名1", "字段名2"); a.Rows.Add("字段值1", "字段值2"); var b = new DataSet(); var c = BuildDataTable("表名A", "字段名A"); c.Rows.Add("字段值A"); b.Tables.Add(c); var danew = new DataSet(); danew.Tables.Add(a); danew.Merge(b); Console.WriteLine(danew.Tables[0].Rows[0]["字段名2"].ToString()); Console.WriteLine(danew.Tables["表名A"].Rows[0]["字段名A"]);
输出
字段值2 字段值A
标签:Tables,初始化,DataSet,cdt,Add,ds,Columns,赋值 来源: https://www.cnblogs.com/jiatree/p/16386151.html