DataTable 的创建,列名读取,文本格式化
1 namespace MyTest 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 Test(); 8 } 9 private static void Test() 10 { 11 //创建一个表 12 DataTable dt = new DataTable("Product"); 13 DataColumn dc = null; 14 15 //添加列,赋值 16 dc = dt.Columns.Add("id", Type.GetType("System.Int32")); 17 dc.AutoIncrement = true; 18 dc.AutoIncrementSeed = 1; 19 dc.AutoIncrementStep = 1; 20 dc.AllowDBNull = false; 21 dt.Columns.Add("pname", Type.GetType("System.String")); 22 dt.Columns.Add("price", Type.GetType("System.Double")); 23 dt.Columns.Add("memo", Type.GetType("System.String")); 24 25 DataRow dr = dt.NewRow(); 26 dr["pname"] = "red apple"; 27 dr["price"] = 9.9; 28 dr["memo"] = "this red apple so red."; 29 dt.Rows.Add(dr); 30 31 dr = dt.NewRow(); 32 dr["pname"] = "black apple"; 33 dr["price"] = 19.9; 34 dr["memo"] = "this black apple so black."; 35 dt.Rows.Add(dr); 36 37 dr = dt.NewRow(); 38 dr["pname"] = "gold apple"; 39 dr["price"] = 29.9; 40 dr["memo"] = "this gold apple so gold."; 41 dt.Rows.Add(dr); 42 43 //取列名 44 List<string> cnameList = new List<string>(); 45 foreach(DataColumn dcn in dt.Columns) 46 { 47 cnameList.Add(dcn.ColumnName); 48 Console.Write($"{String.Format("{0,-12}", dcn.ColumnName)}"); //执行结果:(例)"red apple ",占12位,向左对齐 49 } 50 Console.WriteLine(" "); 51 //根据列名来读取行数据 52 foreach(DataRow row in dt.Rows) 53 { 54 foreach(string cname in cnameList) 55 { 56 string args = row[cname].ToString(); 57 if(args.Length>12) 58 { 59 Console.Write($"{args}"); 60 } 61 else 62 { 63 Console.Write($"{String.Format("{0, -12}", args)}"); 64 } 65 } 66 Console.WriteLine(" "); 67 } 68 } 69 } 70 }
执行结果: