Results 1 to 2 of 2

Thread: [RESOLVED] Index Out of Range

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Aug 2014
    Posts
    92

    Resolved [RESOLVED] Index Out of Range

    I'm dealing with a problem like this, i only want the Image change one time, so i tried this code and it appears the index out of range,
    could anyone explain to me what's the problem of this? and how to fix it?


    Here's the code:

    Code:
    Public Class Mario
    Dim ImageSwitch() As Integer = {0, 0}
    Private Sub Mario_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
            If e.KeyCode = Keys.D Then
                Leftkey = True
    
                If ImageSwitch(1) = 1 Then
                    MainChar.Image = Image.FromFile("C:\Users\user\Documents\StanRun.gif")
                Else
                    ImageSwitch(1) = ImageSwitch(1) + 1
    
                End If
            End If
    
            If e.KeyCode = Keys.A Then
                Rightkey = True
                If ImageSwitch(2) = 1 Then
                    MainChar.Image = Image.FromFile("C:\Users\user\Documents\StanRun.gif")
                Else
                    ImageSwitch(2) = ImageSwitch(2) + 1
    
                End If
            End If

  2. #2
    Frenzied Member
    Join Date
    Feb 2003
    Posts
    1,807

    Re: Index Out of Range

    Your ImageSwitch array contains only two elements and since all arrays in vb.net are base zero, you should be using indexes 0 and 1.

    Code:
    Public Class Mario
    Dim ImageSwitch() As Integer = {0, 0}
    Private Sub Mario_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
            If e.KeyCode = Keys.D Then
                Leftkey = True
    
                If ImageSwitch(0) = 1 Then
                    MainChar.Image = Image.FromFile("C:\Users\user\Documents\StanRun.gif")
                Else
                    ImageSwitch(0) = ImageSwitch(0) + 1
                End If
            End If
    
            If e.KeyCode = Keys.A Then
                Rightkey = True
                If ImageSwitch(1) = 1 Then
                    MainChar.Image = Image.FromFile("C:\Users\user\Documents\StanRun.gif")
                Else
                    ImageSwitch(1) = ImageSwitch(1) + 1
                End If
            End If

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width