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定义相对应。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述