VB.NET 循环通过类似命名的表单控件
好吧,我给你的大脑带来了麻烦。我正在将用 VB6 编写的程序转换为 Visual Studio 2010 VB.Net,但遇到了问题。我试图循环浏览表单上的 20 个表单元素,这些元素都有前缀“chkCustomerItems”,后面有数字 1 到 20。我将其与数据库查找一起使用,以便有一个数据库条目,然后将数据库项目名称应用到复选框的文本字段并打开可见性。这是我写的代码: ConnOpenClose()
Rs = New ADODB.Recordset
Sql = "SELECT * FROM CustomersItems;"
Rs.Open(Sql, Conn)
If Rs.EOF = False Then
tempInteger = 1
Rs.MoveFirst()
Do
tempString = "chkCustomerItems" & tempInteger.ToString
Me.Controls(tempString).Text = Rs.Fields("Item").Value
Me.Controls(tempString).Visible = True
tempInteger = tempInteger + 1
Rs.MoveNext()
If tempInteger = 21 Then GoTo ExitLoop
Loop Until Rs.EOF
ExitLoop:
End If
运行时,出现 NullReferenceException 错误。这基本上是我在 VB6 中使用的代码(对 .NET 基础结构进行了一些更改)。请帮助我找出我做错了什么,目前我必须对所有 20 个项目进行硬编码,虽然它可以工作,但它看起来或运行起来都不漂亮。
先感谢您
Ok, I got a tickler for your brains. I am converting a program I wrote in VB6 to Visual Studio 2010 VB.Net and have run into a problem. I am trying to cycle through 20 form elements on a form that all have the prefix 'chkCustomerItems' and then have a number 1 to 20 behind them. I am using this with a database lookup so that it there is a database entry it then applies the database item name to the checkbox's text field and turns visibility on. Here is the code I wrote:
ConnOpenClose()
Rs = New ADODB.Recordset
Sql = "SELECT * FROM CustomersItems;"
Rs.Open(Sql, Conn)
If Rs.EOF = False Then
tempInteger = 1
Rs.MoveFirst()
Do
tempString = "chkCustomerItems" & tempInteger.ToString
Me.Controls(tempString).Text = Rs.Fields("Item").Value
Me.Controls(tempString).Visible = True
tempInteger = tempInteger + 1
Rs.MoveNext()
If tempInteger = 21 Then GoTo ExitLoop
Loop Until Rs.EOF
ExitLoop:
End If
When it runs, I get a NullReferenceException error. This is basically the code that I used in VB6 (with some changes for .NET infrastructure). Help me please figure out what I am doing wrong, for the time being I am having to hard code all 20 items in, and while it works, it doesn't look nor run pretty.
Thank you in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在使用 Text 属性,因此我假设这是文本框。
试试这个:
you are using Text property so i assume that this is textbox.
try this:
如果您的任何控件嵌入到任何容器控件(面板、选项卡等)中,您将无法通过 Controls 集合索引访问它们。
相反,您需要使用 Controls.Find 并将第二个参数 (searchAllChildren) 设置为 true(我还添加了一些额外的检查和 .Net 处理方法):
If any of your controls are embedded in any container controls (panels, tabs, etc), you will not be able to get to them through the Controls collection indexing.
Instead, you will need to use Controls.Find with the second parameter (searchAllChildren) set to true (I also added some additional checking and .Net ways of doing things):