【问题标题】:Index outside bounds in event handler事件处理程序中的索引外部边界
【发布时间】:2013-04-06 01:58:38
【问题描述】:

我在向lblshipping.text 显示运费时遇到了一些问题

Option Explicit On
Option Strict On
Option Infer Off

Public Class frmMain
    Private intMin() As Integer = {1, 11, 51, 101}
    Private intMax() As Integer = {10, 50, 100}
    Private dblShip() As Double = {15, 10, 5, 0}

    Private Sub btnExit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExit.Click
        Me.Close()
    End Sub

    Private Sub txtordered_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtOrdered.KeyPress
        ' allows the text box to accept numbers and the Backspace key

        If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> ControlChars.Back Then
            e.Handled = True
        End If
    End Sub

    Private Sub txtordered_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtOrdered.TextChanged
        lblShipping.Text = String.Empty
    End Sub

    Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click

        Dim intOrdered As Integer
        Integer.TryParse(txtOrdered.Text, intOrdered)

        For intIndex As Integer = 0 To 3
            If intOrdered <= 2 Then
                If intOrdered >= intMin(intIndex) And intOrdered <= intMax(intIndex) Then
                    lblShipping.Text = dblShip(intIndex).ToString("C2")
                End If
            End If
            If intIndex = 3 Then
                If intOrdered >= intMin(intIndex) Then
                    lblShipping.Text = dblShip(intIndex).ToString("C2")
                End If
            End If
        Next intIndex
    End Sub
End Class

【问题讨论】:

  • 使您的代码最小化并删除不必要的杂物。发布真实代码(你的使用Option Strict On,这很好,但它不会编译!)并具体说明错误——它发生在哪里?您的代码很难分辨。

标签: vb.net indexoutofboundsexception


【解决方案1】:

尝试删除此语句

Private Sub txtordered_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtOrdered.TextChanged
    lblShipping.Text = String.Empty
End Sub

并尝试更改您的 for next 语句

For intIndex As Integer = 0 To 3
        If intOrdered <= 2 Then
            If intOrdered >= intMin(intIndex) And intOrdered <= intMax(intIndex) Then
                lblShipping.Text = dblShip(intIndex).ToString("C2")
            End If
       elseIf intIndex = 3 Then
            If intOrdered >= intMin(intIndex) Then
                lblShipping.Text = dblShip(intIndex).ToString("C2")
            End If
        End If
    Next intIndex

【讨论】:

  • 为什么会有这些变化?他们似乎与 OP 的问题没有任何关系。
  • 删除语句> 因为我认为如果得到这些语句,lbl shipping 将没有价值。关于 for 循环,只是为了最小化代码
猜你喜欢
  • 2020-04-02
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2010-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多