2012-01-11 2 views
0

Привет всем, у меня возникли проблемы с правильным потоком для формы вопроса. Допустим, у меня есть 6 вопросов. Я определяю их как это:Задаваемые вопросы в массиве

Dim firstStart As Boolean = True 
Dim totalQs As Integer = 0 
Dim currentQ As Integer = 0 
Dim theAnswers() As String 
Dim theQuestions() As String = {"Please scan barcode 1 then press NEXT", "" & _ 
           "Please scan barcode 1 then press NEXT", "" & _ 
           "Please scan barcode 1 then press NEXT", "" & _ 
           "Please scan barcode 1 then press NEXT", "" & _ 
           "Please scan barcode 1 then press NEXT", "" & _ 
           "Please scan barcode 1 then press COMPLETE"} 

/Полный код Следующая кнопка выглядит следующим образом:

Private Sub cmdNextFinish_Click(ByVal sender As System.Object, ByVal e As    System.EventArgs) Handles cmdNextFinish.Click 
    Call theQs(currentQ) 
End Sub 

Form_Load выглядит следующим образом:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
    Call theQs(0) 
End Sub 

И теперь установка вопрос выглядит это:

Private Sub theQs(ByRef theQNum As Integer) 
    If firstStart = True And theQNum = 0 Then 
     firstStart = False 
     totalQs = (theQuestions.Length) 
     ReDim theAnswers(totalQs) 
     lblQ.Text = theQuestions(0) 
     cmdNextFinish.Enabled = True 
     cmdNextFinish.Text = "NEXT" 
     Call buttons(theQNum) 
     txtNumber.Text = "" 
     txtNumber.MaxLength = theQuestionTextboxLimits(theQNum) 
     txtNumber.Focus() 
    ElseIf theQNum = 0 Then 'ANSWERING THE FIRST QUESTION 
     theAnswers(currentQ) = "-" & txtNumber.Text 

     If currentQ <> totalQs Then 
      currentQ = currentQ + 1 
      lblQ.Text = theQuestions(currentQ) 

      If (totalQs - currentQ) = 0 Then 
       cmdNextFinish.Text = "Complete" 
      Else 
       cmdNextFinish.Text = "NEXT" 
      End If 

      txtNumber.Text = "" 
      txtNumber.MaxLength = theQuestionTextboxLimits(theQNum) 
      txtNumber.Focus() 
      Call buttons(currentQ) 
     Else 
      'Call writeXMLFile() 
      MsgBox("exited") 
     End If 
    ElseIf theQNum = 1 Then 'ANSWERING THE SECOND QUESTION 
     theAnswers(currentQ) = txtNumber.Text 

     If theQNum <> totalQs Then 
      currentQ = currentQ + 1 
      lblQ.Text = theQuestions(currentQ) 

      If (totalQs - currentQ) = 0 Then 
       cmdNextFinish.Text = "Complete" 
      Else 
       cmdNextFinish.Text = "NEXT" 
      End If 

      txtNumber.Text = "" 
      txtNumber.MaxLength = theQuestionTextboxLimits(theQNum) 
      txtNumber.Focus() 
      Call buttons(currentQ) 
     Else 
      'Call writeXMLFile() 
      MsgBox("exited") 
     End If 
    ElseIf theQNum = 2 Then 'ANSWERING THE THIRD QUESTION 
     theAnswers(currentQ) = txtNumber.Text 

     If theQNum <> totalQs Then 
      currentQ = currentQ + 1 
      lblQ.Text = theQuestions(currentQ) 

      If (totalQs - currentQ) = 0 Then 
       cmdNextFinish.Text = "Complete" 
      Else 
       cmdNextFinish.Text = "NEXT" 
      End If 

      txtNumber.Text = "" 
      txtNumber.MaxLength = theQuestionTextboxLimits(theQNum) 
      txtNumber.Focus() 
      Call buttons(currentQ) 
     Else 
      'Call writeXMLFile() 
      MsgBox("exited") 
     End If 
    ElseIf theQNum = 3 Then 'ANSWERING THE FORTH QUESTION 
     theAnswers(currentQ) = txtNumber.Text 

     If theQNum <> totalQs Then 
      currentQ = currentQ + 1 
      lblQ.Text = theQuestions(currentQ) 

      If (totalQs - currentQ) = 0 Then 
       cmdNextFinish.Text = "Complete" 
      Else 
       cmdNextFinish.Text = "NEXT" 
      End If 

      txtNumber.Text = "" 
      txtNumber.MaxLength = theQuestionTextboxLimits(theQNum) 
      txtNumber.Focus() 
      Call buttons(currentQ) 
     Else 
      'Call writeXMLFile() 
      MsgBox("exited") 
     End If 
    ElseIf theQNum = 4 Then 'ANSWERING THE FIFTH QUESTION 
     theAnswers(currentQ) = txtNumber.Text 

     If theQNum <> totalQs Then 
      currentQ = currentQ + 1 
      lblQ.Text = theQuestions(currentQ) 

      If (totalQs - currentQ) = 0 Then 
       cmdNextFinish.Text = "Complete" 
      Else 
       cmdNextFinish.Text = "NEXT" 
      End If 

      txtNumber.Text = "" 
      txtNumber.MaxLength = theQuestionTextboxLimits(theQNum) 
      txtNumber.Focus() 
      Call buttons(currentQ) 
     Else 
      'Call writeXMLFile() 
      MsgBox("exited") 
     End If 
    ElseIf theQNum = 5 Then 'ANSWERING THE SIXTH QUESTION 
     theAnswers(currentQ) = txtNumber.Text 

     If theQNum <> totalQs Then 
      currentQ = currentQ + 1 
      lblQ.Text = theQuestions(currentQ) 

      If (totalQs - currentQ) = 0 Then 
       cmdNextFinish.Text = "Complete" 
      Else 
       cmdNextFinish.Text = "NEXT" 
      End If 

      txtNumber.Text = "" 
      txtNumber.MaxLength = theQuestionTextboxLimits(theQNum) 
      txtNumber.Focus() 
      Call buttons(currentQ) 
     Else 
      'Call writeXMLFile() 
      MsgBox("exited") 
     End If 
    End If 
End Sub 

Кажется, я смущаюсь, потому что, когда он доходит до 5-го вопроса, он дает мне ошибку . Индекс находился за пределами массива. на линии

lblQ.Text = theQuestions(currentQ) 

для theQNum = 5

Я знаю его на 5-й вопрос, но массив не идти до 6.

Что я делаю неправильно здесь (или overthinking что-то простое)

Спасибо,

Дэвид

UPDATE GOT IT

Private theQNum As Integer 

Sub Start 
    theQNum =0 
    SetupNextQuestion 
End Sub 

Sub SetupNextQuestion 
    txtNumber.Text = "" 
    lblQuestion.Text = theQuestions(theQNum) 

    If theQNum = (theQuestions.Length - 1) Then 
     cmdNextFinish.Text = "Complete" 
    Else 
     cmdNextFinish.Text = "NEXT" 
    End If 

End Sub 

Sub cmdNextFinish_Click 
    theAnswers(theQNum) = txtNumber.Text 

    'Check if this is a finish 
    theQNum += 1 
    If theQNum >= theQuestions.Length Then 
     'Call writeXMLFile() 
     MsgBox("exited") 
    Else 
     SetupNextQuestion 
    End If 
End Sub 

Дэвид

ответ

0

Массивы начинаются с 0 года. Итак, ваш первый вопрос в индексе 0 & шестой вопрос находится в индексе 5 в массиве. Если вы увеличиваете индекс заранее для последнего вопроса, индекс становится равным 6, который не имеет значения.

+0

Все еще дает ошибку ** Индекс находился за пределами массива ** Это число должно быть на 1 вперед, так как QNum на нем (скажем 0) необходимо загрузить следующий вопрос (1) после нажатия пользователем NEXT , – StealthRT

+0

Почему вы увеличиваете значение currentQ. Значение currentQ станет 6.Массив начинается с 0, что означает, что шестой вопрос - это QQuestions (5) – Harsh

+0

Так как это то, что заполняется при нажатии кнопки, чтобы кнопка NEXT включалась в 1, каждый раз обходился, пока не получил последний вопрос, где COMPLETE будет на кнопке. – StealthRT

1

Эти строки:

If theQNum <> totalQs Then 
      currentQ = currentQ + 1 
      lblQ.Text = theQuestions(currentQ) 

которые являются внутри If для ElseIf theQNum = 5 Then то, что заставляет вас выйти за пределы. Но проблема намного раньше в вашем if. Вы начинаете с

If firstStart = True And theQNum = 0 Then 
     ' Code here 
ElseIf theQNum = 0 Then 'ANSWERING THE FIRST QUESTION 
     'More code here that doesn't get called 

Это ElseIf theQNum = 0 не будет вызываться при первом запуске, так как первая часть, если это правда. И в этом первом бите кода, когда firstStart имеет значение true, вы не увеличиваете currentQ, так что в следующий раз, когда этот sub называется firststart, это false, а currentQ все равно 0. Корень вашей проблемы.

Простое исправление заключается в том, чтобы увеличить ваш текущийQ внутри первого бита вашего if и всегда задавать текст метки ПЕРЕД вы увеличиваете currentQ. И не увеличивайте его, когда вы находитесь на последнем вопросе. Таким образом, currentQ никогда не выйдет за пределы диапазона.

Смежные вопросы