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类就可以了,
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”,运行程序,则可以对记录进行编辑了,如下图: