标签:core 遍历 insert 建议 clear ble 位置 move eve
1 private void button1_Click(object sender, EventArgs e) 2 { 3 DataTable dt1 = new DataTable(); 4 dt1.Columns.Add("ID", typeof(string)); 5 dt1.Columns.Add("NAME", typeof(string)); 6 dt1.Columns.Add("AGE", typeof(int)); 7 dt1.Columns.Add("SEX", typeof(string)); 8 9 dt1.PrimaryKey = new DataColumn[] { dt1.Columns["ID"] }; 10 for (int i = 0; i < 5; i++) 11 { 12 DataRow dr = dt1.NewRow(); 13 dr["ID"] = "00" + i.ToString(); 14 dr["NAME"] = "00-" + i.ToString(); 15 dr["AGE"] = 15 + i; 16 dr["SEX"] = "M"; 17 dt1.Rows.Add(dr); 18 19 } 20 DataTable dt2 = new DataTable(); 21 dt2.Columns.Add("ID", typeof(string)); 22 dt2.Columns.Add("NAME", typeof(string)); 23 dt2.Columns.Add("Course", typeof(string)); 24 dt2.Columns.Add("Score", typeof(int)); 25 26 dt2.PrimaryKey = new DataColumn[] { dt2.Columns["ID"] }; 27 for (int i = 0; i < 5; i++) 28 { 29 DataRow dr = dt2.NewRow(); 30 dr["ID"] = "00" + i.ToString(); 31 dr["NAME"] = "00-" + i.ToString(); 32 dr["Course"] = "C#"; 33 dr["Score"] = i + 80; 34 dt2.Rows.Add(dr); 35 } 36 //Merge 37 dt1.Merge(dt2); 38 //Copy 39 var dt3 = dt1.Copy();//Copy,复制表的结构以及数据 40 //Clone 41 var dt4 = dt2.Clone();//Clone,复制表的结构、约束信息 42 43 //对DataTable的操作 44 DataRow dr1 = dt3.NewRow(); 45 dr1["ID"] = "005"; 46 dr1["NAME"] = "00-5"; 47 dr1["AGE"] = 15; 48 dr1["SEX"] = "F"; 49 dt3.Rows.InsertAt(dr1, 2);//表的指定位置插入新增加的一行 50 51 dt3.Columns.Add(new DataColumn() { ColumnName = "Memo", DataType = typeof(string) });//默认插入到最后一列 52 dt3.Columns["Memo"].SetOrdinal(0);//把插入的列移动到第一行 53 54 int memoIndex = dt3.Columns.IndexOf("Memo");//获取列的位置信息 55 var isContainName = dt3.Columns.Contains("NAME");//判断table中是否存在某列 56 57 List<string> columnsNameList = new List<string>();//遍历获取table的所有列名 58 foreach (DataColumn col in dt3.Columns) 59 { 60 columnsNameList.Add(col.ColumnName); 61 } 62 63 dt3.Columns.RemoveAt(memoIndex);//通过列名的索引进行移除 64 dt3.Columns.RemoveAt(2);//通过列名的索引进行移除 65 dt3.Columns.Remove("SEX");//通过列名进行移除,建议使后者 66 67 string[] name = new string[dt3.Rows.Count];//方法一:对表中的数据进行遍历输出 68 string[] id = new string[dt3.Rows.Count]; 69 for (int i = 0; i < dt3.Rows.Count; i++) 70 { 71 name[i] = dt3.Rows[i]["NAME"].ToString(); 72 id[i] = dt3.Rows[i]["ID"].ToString(); 73 } 74 75 dt3.Clear();//清空表中的数据 76 }
标签:core 遍历 insert 建议 clear ble 位置 move eve
原文地址:https://www.cnblogs.com/lgx5/p/12227978.html