根据 DataReader 数据填充对象数组

发布于 2024-09-07 21:33:07 字数 716 浏览 0 评论 0原文

我不确定如何正确表达我的问题,但我想实现这样的目标。

我有一个名为 Products 的类,

public class Products

private ID as Integer

private Name as String

Public Property ProductID()
  Get
    Return ID
  End Get
  Set(ByVal value)
    ID = value
  End Set
End Property

在我的一个代码隐藏页面中,我从 SQL 命令检索数据并将其放入 datareader 对象中。

我如何才能声明该类,以便数据读取器中的每一行实际上都是该类的实例?

例如:

Dim myProduct() as New Product
Dim intCnt as Integer 

While datareaderData.read()
  intCnt += 1
  myProduct(intCnt) = new Product
  myProduct(intCnt).ID = datareaderData("ID")
  myProduct(intCnt).Name = datareaderData("Name")
End While

当我执行相同操作时,我收到错误“对象引用未设置为对象的实例”。

我对此感到非常困惑。非常感谢任何提示。谢谢。

I am not sure how to phrase my question properly but I want to achieve something like this.

I have a class named Products

public class Products

private ID as Integer

private Name as String

Public Property ProductID()
  Get
    Return ID
  End Get
  Set(ByVal value)
    ID = value
  End Set
End Property

In one of my code behind pages, I am retrieving data from an SQL Command and placing the same into a datareader object.

How would I be able to declare the class so that each row in my datareader would actually be an instance of the said class?

Like for example:

Dim myProduct() as New Product
Dim intCnt as Integer 

While datareaderData.read()
  intCnt += 1
  myProduct(intCnt) = new Product
  myProduct(intCnt).ID = datareaderData("ID")
  myProduct(intCnt).Name = datareaderData("Name")
End While

When I do the same, I am getting an error "Object Reference Not Set to an Instance of an Object.

I am quite stumped on this one. Any tips greatly appreciated. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷荒 2024-09-14 21:33:07

您应该使用 Arraylist 或 - 更好 - 通用列表(产品)。
此外,我
强烈建议设置选项严格打开 在项目的编译器设置中。

Dim products As New List(Of Product)
While datareaderData.read()
    Dim nextProduct As New Product
    nextProduct.ProductID = CType(datareaderData("ID"), System.Int32)
    nextProduct.Name = datareaderData("Name").ToString
    products.add(nextProduct)
End While

You should use an Arraylist or -better- a generic List(of Product).
Besides i would strongly recommend to set Option Strict On in your project's Compiler Settings.

Dim products As New List(Of Product)
While datareaderData.read()
    Dim nextProduct As New Product
    nextProduct.ProductID = CType(datareaderData("ID"), System.Int32)
    nextProduct.Name = datareaderData("Name").ToString
    products.add(nextProduct)
End While
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文