【问题标题】:Concatenation of variable name being passed in .Net VB [closed]在.Net VB中传递的变量名的串联[关闭]
【发布时间】:2014-11-20 21:53:55
【问题描述】:

我设置了 20 多个文本框,我想要做的是从每个文本框中取出值并将其放入一个值数组(结构)。我的每个文本框都有一个 txtScore00、01、02 等名称,我试图用计数器循环它们并将计数器用作变量名中的数字。我找到了这个主题Concatenate Variable Names in VB,但我仍然无法让它工作。有什么建议么?我的代码填充数组:

For intCountOne = 0 To aStudent.Length - 1
        For intCountTwo = 0 To aStudent(intCountOne).decGrade.Length - 1
            aStudent(intCountOne).decGrade(intCountTwo) = Me.Controls("tbScore" & intCountOne & intCountTwo).Text

【问题讨论】:

  • 你为什么要删除你的代码?
  • 尝试添加 4 个空格使其看起来像代码但没有用,不想让问题看起来像垃圾
  • @LittleB0Y,留下代码,其他人会编辑让它看起来不错。
  • 当我填写方框时,它说对象引用未设置为对象。
  • What is a NullReferenceException and how do I fix it? 可能重复,您的数组可能未初始化

标签: .net vb.net concatenation


【解决方案1】:

你有:

Me.Controls("tbScore" & intCountOne & intCountTwo)

这要求表单直接包含文本框。如果它们位于不同的容器中,例如 Panel,那么您需要将“Me”更改为容器的名称(例如“Panel1”)。

或者,您可以在表单中搜索具有该名称的控件,如果文本框分布在多个容器中,这将非常有用(如果它们都在同一个容器中,它仍然可以工作)容器)。

这是一个简单的例子:

    Dim matches() As Control
    For intCountOne = 0 To aStudent.Length - 1
        For intCountTwo = 0 To aStudent(intCountOne).decGrade.Length - 1
            matches = Me.Controls.Find("tbScore" & intCountOne & intCountTwo, True)
            If matches.Length > 0 AndAlso TypeOf matches(0) Is TextBox Then
                Dim tb As TextBox = DirectCast(matches(0), TextBox)
                aStudent(intCountOne).decGrade(intCountTwo) = tb.Text
            End If
        Next
    Next

【讨论】:

  • 想通了,问题是我在一个组框中循环了所有这些,摆脱了它并且完美地工作
  • 是的...可能是因为我所说的原因。我猜你把控件从 GroupBox 移到了 Form 上?如果您使用我在上面发布的代码,那么它们在哪个容器中并不重要,因为它们总会被找到。
猜你喜欢
  • 1970-01-01
  • 2022-07-28
  • 1970-01-01
  • 2021-06-17
  • 2012-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多