asp.net中数据链路层的创建(5)

 

按“完成”按钮结束向导。在向导关闭后,我们回到DataSet设计器中,它会显示我们刚创建的DataTable。你可 以看到Products DataTable的字段列单(ProductID, ProductName 等),还有ProductsTableAdapterFill()GetProducts()方法 。

图 12: Products DataTable和ProductsTableAdapter被添加到强类 型DataSet中

至此,我们生成了含有单一DataTable类(Northwind.Products)的强类型DataSet以及一个含 有GetProducts()方法的强类 型DataAdapter类(NorthwindTableAdapters.ProductsTableAdapter)。通过这些对象可以用下 列编码来获取所有产品的列单:

C#
1
2
3
4
5
6
7
NorthwindTableAdapters.ProductsTableAdapter 

productsAdapter = new

NorthwindTableAdapters.ProductsTableAdapter();
Northwind.ProductsDataTable products;

products = productsAdapter.GetProducts();

foreach (Northwind.ProductsRow productRow in products)
Response.Write("Product: " +

productRow.ProductName + "
");

这段编码不要求我们写一行的跟数据访问有关的编码。我们不需要生成任何ADO.NET类的实例,我们不需要 指明任何连接字符串,任何SQL查询语句,或者任何存储过程。TableAdapter为我们提供了底层的数据访问编 码!

这个例子里的每个对象都是强类型的,允许Visual Studio提供IntelliSense帮助以及编译时类型检查。最棒 的是,从TableAdapter 返回的DataTable可以直接绑定到ASP.NET数据Web 控件上去,这样的控件包 括GridView,DetailsView,DropDownList,CheckBoxList,以及另外几个控件。下面这个例子示范只要 在Page_Load事件处理函数里添加短短的三行编码就能将从GetProducts()方法返 回的DataTable绑定到一个GridView上去。

AllProducts.aspx

ASP.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<%@ Page Language="C#" 

AutoEventWireup="true" CodeFile="AllProducts.aspx.cs"

Inherits="AllProducts" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0

Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>View All Products in a GridView title>
<link href="Styles.css"

rel="stylesheet"

type="text/css"

/>
head>
<body>
<form id="form1" runat="server">
<div>
<h1>
All Products h1>
<p>
<asp:GridView ID="GridView1" runat="server"
CssClass="DataWebControlStyle">
<HeaderStyle CssClass="HeaderStyle" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
asp:GridView>
  p>

div>
form>
body>
html>

AllProducts.aspx.cs

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NorthwindTableAdapters;

public partial class

AllProducts : System.Web.UI.Page
{
protected void

Page_Load(object sender, EventArgs e)
{
ProductsTableAdapter productsAdapter = new
ProductsTableAdapter();
GridView1.DataSource = productsAdapter.GetProducts();
GridView1.DataBind();
}
}

图 13: 显示在GridView里的产品列单

这个例子要求我们在ASP.NET网页的Page_Load事件处理函数里,写三行编码。在以后的教程里,我们将讨 论使用ObjectDataSource,用声明的方式来从DAL中获取数据。用ObjectDataSource的话,我们一行编码都不 用写,而且还能得到分页和排序支持呢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值