dataTable使用方法
using System; using System.Data; using System.Data.SqlClient; namespace App{ class MyClass{ public static void Main(string[] args){ //DataTable dt = new DataTable(); int[] id = { 4, 5, 1, 3, 2, 7, 6 }; string[] name = {"Tom","Jack","HelloWorld","Visual Studio","Gril","Timmy","Geo" }; DataTable dt = new DataTable("Table_New"); //DataColumn dc = new DataColumn(); dt.Columns.Add("id",typeof(int)); dt.Columns.Add("name",typeof(string)); for(int i=0;i<id.Length;i++){ dt.Rows.Add(new object[]{id[i],name[i]});//添加一个数组 } //遍历dataTables; for(int i=0;i<id.Length;i++){ Console.WriteLine(dt.Rows[i]["name"]); } } } }
把 dataDable 比作一个excel或数据表
先添加列,在添加行
读取DataTable行列数:
dt.Rows.Count
dt.Columns.Count
练习:
using System; using System.Data; namespace App{ class MyClass{ public static void Main(string[] args){ DataTable dt = new DataTable("table"); dt.Columns.Add("id"); dt.Columns.Add("name"); int[] idArr={1,2,3}; string[] nameArr ={"mlh","1421","ghh"}; for(int i=0;i<idArr.Length;i++){ dt.Rows.Add(idArr[i],nameArr[i]); } for(int i=0;i<idArr.Length;i++){ Console.WriteLine(dt.Rows[i]["id"]); } } } }