【问题标题】:Error in Visual Basic loopVisual Basic 循环中的错误
【发布时间】:2018-07-16 08:57:02
【问题描述】:

显然我在循环的第二个 if 条件中弄错了,我留下一张图片以便更好地理解。

由于某种原因,即使它们几乎相同,错误也不会在第一个 if 条件中显示。

为了把它放在上下文中,我有一个大的第一个文本框和其他 9 个小文本框。基本上我想把我写在大文本框中的值一个一个地发送给小的。

大文本框名称属性是 t0 而其他从 t1 到 t9

视觉基本代码

 Public Class Form1

        Dim array() As TextBox = {t1, t2, t3, t4, t5, t6, t7, t8, t9}

        Private Sub t0_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles t0.KeyDown
            If e.KeyCode = Keys.Enter Then

                If sender.Text.ToString <> String.Empty Then

                    For indice As Integer = 0 To array.Length - 1

                        If array(indice).Text = String.Empty Then '<== The error is in this line

                            array(indice).Text = sender.Text.ToString

                            Exit For

                        End If

                    Next

                End If

            End If

        End Sub

    End Class

更新

Used等于这次,但仍然是同样的错误

【问题讨论】:

  • 所以,您的数组似乎没有此索引或值为 null ;)
  • 你是对的,声明文本框数组的正确方法是什么,显然我的有问题。请注意,我将文本框元素名称更改为 t0 到 t9

标签: vb.net


【解决方案1】:

您的array 中的一项似乎是Nothing。您可以通过使用以下if 条件(使用AndAlso)来避免此类错误:

If TypeOf(array(indice)) Is TextBox AndAlso array(indice).Text = String.Empty Then
    array(indice).Text = sender.Text.ToString
    Exit For
End If

注意:您的第一个if 条件不使用array,因此错误不会在那里发生。

但问题不在于if 条件!您将array 定义为早期。在您定义array 时,表单的控件尚未初始化(因此每个控件都是Nothing,直到在方法/构造函数New 中调用InitializeComponent)。

您可以直接在KeyDown 事件上初始化array,以确保创建/初始化TextBox 元素。

Private Sub t0_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles t0.KeyDown
    If e.KeyCode = Keys.Enter Then
        If sender.Text.ToString <> String.Empty Then
            Dim array() As TextBox = {t1, t2, t3, t4, t5, t6, t7, t8, t9}

            For indice As Integer = 0 To array.Length - 1
                If TypeOf(array(indice)) Is TextBox AndAlso array(indice).Text = String.Empty Then
                    array(indice).Text = sender.Text.ToString
                    Exit For
                End If
            Next
        End If
    End If
End Sub

另一个在全局范围内使用array 的解决方案是在Load 事件中初始化array

【讨论】:

  • 你是对的,我的数组索引似乎为空,声明文本框数组的正确方法是什么?请注意,我将文本框名称属性更改为 t0 到 t9
  • 非常感谢,您的解决方案按预期工作,我将声明放在加载方法中并且效果也很好,是否有任何解释为什么它不能将数组声明为表单方法。跨度>
  • 看到更新,我现在明白了,因为在 android 中有一些方法会自动调用并会加载界面和组件,因此在加载之前您不能引用这些组件。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-02-16
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多