2.0中的DataSource系列控件

2018-09-06 12:59

阅读:472

  

Sqldatasource控件----用于连接sql数据库的数据源控件
Accessdatasource控件----用于连接access数据库的数据源控件
ObjectDataSource控件----用于连接自定义对象的数据源控件
DataSetDataSource控件-----将XML文件做为dataset并进行相关处理的控件
XmlDataSource控件-----该控件装载Xml文件,并绑定到datagrid、datalist等控件中
SiteMapDataSource控件-----该控件装载一个预先定义好的站点布局文件,之后将其与treenode树形控件或Sitemappath控件绑定,以实现方便地制作站点的页面导航功能。

下图显示了2005 Express beta 1中,Datasource的六种控件:


本文中,将重点介绍ObjectDataSource控件,DataSetDataSource控件和XmlDataSource控件,而sqldatasource控件的介绍,请参考《使用2.0中的GridView控件》,该文中介绍了sqldatasource控件的使用方法,而accessdatasource控件,则与sqldatasource 控件类似,只不过连接的数据库是access。

ObjectDataSource控件

该控件,将用户自己创建的对象绑定到数据控件中,比如绑定到datagrid,gridview。下面来看个例子,在visual studio 2005 beta 1中,创建新的站点,并添加一个新的类,名称叫Products:

Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient

Public Class Products
Public Function getProducts() As DataSet
Dim conn As New SqlConnection(Server=(local);Integrated Security=True;Database=Northwind;Persist
Security Info=True)
Dim adapter As New SqlDataAdapter(SELECT [ProductID], [ProductName], [SupplierID], [CategoryID],
[QuantityPerUnit], [UnitPrice] FROM [Products], conn)

Dim ds As New DataSet
adapter.Fill(ds, Products)
Return ds
End Function
End Class
Product类包含了getproducts方法,该方法返回Northwind数据库中所有的产品,以dataset形式返回。使用objectdatasource 控件,可以将自定义的类绑定到数据控件中,而只需要将ojectdatasource 控件拖拉到设计窗体中,之后,点击Configure Data Source…链接,在弹出的窗体中(如下图),选择要绑定的类,此时选择Product类就可以了,


在下一步中,选择要绑定哪一个类中的相关方法,如下图:


在下一步中,将可以选择执行什么样的SQL语句,比如select,update,insert,delete等操作,本文中只需要返回Product数据,所以选择select就可以了,之后点FINISH完成操作。

接着,拖拉一个gridview控件到窗体中,将其绑定到刚才我们创建的objectdatasource 控件,并将Enable Paging, Enable Scripting, Enable Selection三个选择框打勾,如下图:


之后运行程序,就可以看到结果。如果要对ojectdatasource 控件进行编辑的话,就要另外提供一个方法了,我们加入一个叫updateProducts的方法,如下:

Public Sub updateProducts(ByVal ProductID As Integer, ByVal ProductName As String, _
ByVal SupplierID As Integer, ByVal CategoryID As Integer, _
ByVal QuantityPerUnit As String, ByVal UnitPrice As Double)
Dim conn As New SqlConnection(Server=(local);Integrated Security=True;Database=Northwind;Persist Security
Info=True)
Dim adapter As New SqlDataAdapter(SELECT * FROM Products WHERE ProductID= ProductID, conn)
Dim ds As New DataSet
adapter.Fill(ds, Products)
With ds.Tables(0).Rows(0)
.Item(ProductName) = ProductName
.Item(SupplierID) = SupplierID
.Item(CategoryID) = CategoryID
.Item(QuantityPerUnit) = QuantityPerUnit
.Item(UnitPrice) = UnitPrice
End With
Dim cb As New SqlCommandBuilder(adapter)
adapter.Update(ds, Products)
End Sub
之后再绑定到objectdatasource控件,并选用其中的UPDATE选项卡中的updateProducts方法,并在绑定到gridview控件时,选择“Enable Editing option”,运行程序,则可以对记录进行编辑了,如下图:

  

本新闻共2页,当前在第1页12

  


评论


亲,登录后才可以留言!