DataTable的列操作
public DataTable GenerateTable() { //对Table1添加列名,并设置列值类型 DataTable dt1 = new DataTable();//创建Table dt1.Columns.Add("ID", typeof(string)); dt1.Columns.Add("NAME", typeof(string)); dt1.Columns.Add("AGE", typeof(System.Decimal)); dt1.Columns.Add("SEX", typeof(string)); //此列放置的顺序 dt1.Columns["SEX"].SetOrdinal(2); //对Table1进行设置KEY dt1.PrimaryKey = new DataColumn[] { dt1.Columns["ID"] }; //对Tabel添加数值 for (int i = 0; i < 5; i++) { DataRow dr = dt1.NewRow(); dr["ID"] = "00" + i.ToString(); dr["NAME"] = "00-" + i.ToString(); dr["AGE"] = 15 + i; dr["SEX"] = "M"; dt1.Rows.Add(dr); } //对数据行进行资料筛选 dt1.Select("AGE > 20", "AGE ASC"); //筛选 dt1.DefaultView.RowFilter = "AGE > 20"; dt1 = dt1.DefaultView.ToTable(); //排序 dt1.DefaultView.Sort = "ID DESC,AGE ASC"; dt1 = dt1.DefaultView.ToTable(); //添加一行空行 注:各列必须没有Key值限制 dt1.DefaultView.AddNew(); dt1 = dt1.DefaultView.ToTable(); //只显示部分列,重复列值删去 DataTable dtTemp = dt1.DefaultView.ToTable(true, new string[] { "SEX", "AGE" }); return dt1; }