1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.UI;
6 using System.Web.UI.WebControls;
7 using System.Data;
8 using System.Data.OleDb;
9
10 public partial class Default3 : System.Web.UI.Page
11 {
12 protected void Page_Load(object sender, EventArgs e)
13 {
14 var products = from product in GetDataTable().AsEnumerable()
15 select new { ProductID = product.Field<int>("产品ID"), ProductName = product.Field<string>("产品名称")};
16 this.GridView1.DataSource = products;
17 this.GridView1.DataBind();
18 }
19
20 private DataTable GetDataTable()
21 {
22 DataTable table = new DataTable();
23 using (OleDbConnection conn = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Server.MapPath("~/App_Data/Northwind.mdb")))
24 {
25 using (OleDbCommand comm = new OleDbCommand())
26 {
27 comm.Connection = conn;
28 comm.CommandText = "SELECT * FROM Products";
29 comm.CommandType = CommandType.Text;
30 conn.Open();
31 table.Load(comm.ExecuteReader(CommandBehavior.CloseConnection));
32 }
33 }
34 return table;
35 }
36 }
37
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.UI;
6 using System.Web.UI.WebControls;
7 using System.Data;
8 using System.Data.OleDb;
9
10 public partial class Default3 : System.Web.UI.Page
11 {
12 protected void Page_Load(object sender, EventArgs e)
13 {
14 var products = from product in GetDataTable().AsEnumerable()
15 select new { ProductID = product.Field<int>("产品ID"), ProductName = product.Field<string>("产品名称")};
16 this.GridView1.DataSource = products;
17 this.GridView1.DataBind();
18 }
19
20 private DataTable GetDataTable()
21 {
22 DataTable table = new DataTable();
23 using (OleDbConnection conn = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Server.MapPath("~/App_Data/Northwind.mdb")))
24 {
25 using (OleDbCommand comm = new OleDbCommand())
26 {
27 comm.Connection = conn;
28 comm.CommandText = "SELECT * FROM Products";
29 comm.CommandType = CommandType.Text;
30 conn.Open();
31 table.Load(comm.ExecuteReader(CommandBehavior.CloseConnection));
32 }
33 }
34 return table;
35 }
36 }
37
可以通过调用DataTable的扩展方法AsEnumerable方法,返回IEnumerable<T>对象,便于LINQ查询。
Field<int>("产品ID")功能相当于传统的DataRow["产品ID"],差别是Field语法针对特定的字段值,提供了强类型的支持。指定<T>类型,该类型必须与数据库的Schema定义相对应。