DataTabel 与DataView之间的转化

DataTable转为DataView,或者反之转化, 
使用的是文档/试图模型,DataTable可以有多个视图,这样就可以不需要借助List类型对dataTable数据进行筛选或者排序

 //DataRow row = table.NewRow();
 //row.ItemArray = new object[] { 1, "Fruit", "Apple", 14 };
 //table.Rows.Add(row);

 //row = table.NewRow();
 //row.ItemArray = new object[] { 2, "Fruit", "Orange", 27 };
 //table.Rows.Add(row);


DataTable dt = new DataTable(); dt.Columns.Add("Id",typeof(int));System.Type.GetType("System.Int32") dt.Columns.Add("Name",typeof(string)); dt.Columns.Add("Age", typeof(int)); dt.Columns.Add("Address",typeof(string)); { DataRow dr = dt.NewRow(); dr["Id"] = 1; dr["Name"] = "张三"; dr["Age"] = "13"; dr["Address"] = "杭州"; dt.Rows.Add(dr); } { DataRow dr = dt.NewRow(); dr["Id"] = 2; dr["Name"] = "李四"; dr["Age"] = "20"; dr["Address"] = "杭州"; dt.Rows.Add(dr); } { DataRow dr = dt.NewRow(); dr["Id"] = 3; dr["Name"] = "王五"; dr["Age"] = "60"; dr["Address"] = "杭州"; dt.Rows.Add(dr); } { DataRow dr = dt.NewRow(); dr["Id"] = 4; dr["Name"] = "赵六1"; dr["Age"] = "37"; dr["Address"] = "杭州"; dt.Rows.Add(dr); } //dataTable 转dataView的集中方式 //DataView dv1 = new DataView(dt); //DataView dv1 = dt.AsDataView(); //DataView dv1 = new DataView(); dv1.Table = dt; DataView dv = dt.DefaultView; //多条件筛选 若是字段与条件的类型不一致会报错 //dv.RowFilter = "Age >30"; //dv.RowFilter = "Name like '%赵六%'"; //dv.RowFilter = "Name='赵六'"; //排序 //dv.Sort = "Age desc"; //dv.Sort = "Age asc"; //根据字段长度控制显示 //dv.RowFilter = "Len(Name)>2";

           //dataView转为dataTable的时候 可以指定显示的字段
           //DataTable dt1= dv.ToTable(true,new string[] {"Id","Name" });
           //DataTable dd2 = dv.ToTable(true,"Id","Name","Age");

 

posted @ 2017-06-23 14:54  zmztyas  阅读(7526)  评论(0编辑  收藏  举报