我使用下面提到的Ado.net函数和结果集绑定到网格视图,但是我得到了结果集中的重复行。
请帮帮我。
谢谢
Private _products As New List(Of Product)
Public Property Products As List(Of BusinessObjects.Product)
Get
Return _products
End Get
Set(ByVal value As List(Of BusinessObjects.Product))
_products = value
End Set
End Property
Public Function GetProductDetails() As List(Of Product)
Dim product As New BusinessObjects.Product
Using connection As New SqlConnection
connection.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
connection.Open()
Using Command As New SqlCommand("select * from T_product", connection)
Dim rdr As SqlDataReader
rdr = Command.ExecuteReader
While rdr.Read()
product.ProductID = rdr("ProductID")
product.ProductName = rdr("ProductName")
Products.Add(product)
End While
GridView1.DataSource = Products
GridView1.DataBind()
End Using
End Using
Return Products
End Function
答案 0 :(得分:1)
问题是您每次都在更新和添加相同的产品。在While循环中创建产品对象,如下所示。
Public Function GetProductDetails() As List(Of Product)
Using connection As New SqlConnection
connection.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
connection.Open()
Using Command As New SqlCommand("select * from T_product", connection)
Dim rdr As SqlDataReader
rdr = Command.ExecuteReader
While rdr.Read()
Dim product As New BusinessObjects.Product ' product object create here
product.ProductID = rdr("ProductID")
product.ProductName = rdr("ProductName")
Products.Add(product)
End While
GridView1.DataSource = Products
GridView1.DataBind()
End Using
End Using
Return Prod
答案 1 :(得分:1)
在阅读Dim product As New BusinessObjects.Product
实例
SqlDataReader
初始化
Set(ByVal value As List(Of BusinessObjects.Product))
_products = value
End Set
End Property
Public Function GetProductDetails() As List(Of Product)
Using connection As New SqlConnection
connection.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
connection.Open()
Using Command As New SqlCommand("select * from T_product", connection)
Dim rdr As SqlDataReader
rdr = Command.ExecuteReader
While rdr.Read()
Dim product As New BusinessObjects.Product
product.ProductID = rdr("ProductID")
product.ProductName = rdr("ProductName")
Products.Add(product)
End While
GridView1.DataSource = Products
GridView1.DataBind()
End Using
End Using
Return Products
End Function