0

我正在使用下面提到的 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
4

2 回答 2

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
于 2012-06-20T09:18:24.690 回答
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
于 2012-06-20T09:19:30.880 回答