Paul
Paul

Reputation: 266

Avoid infinite loop while waiting for user input in a form

I am trying to create a prompt, similar to the InputBox function, that allows the user to select an option from an array at runtime. Here is what I have so far:

Private Function prompt_user_combobox(ByVal datasource() As String) As Integer
    Dim cbox As New ComboBox
    With cbox
        .Size = New Size(200, 20)
        .Location = New Size(20, 20)
        .DataSource = datasource
    End With
    Dim btn As New Button
    With btn
        .Size = New Size(80, 20)
        .Text = "Submit"
        .Location = New Size(80, 60)
        .Name = "Button"
    End With
    AddHandler btn.Click, AddressOf cboxSubmitPressed
    Dim form1 As Form = New Form
    form1.Size = New Size(240, 100)
    form1.Name = "cboxSelectForm"
    form1.Controls.Add(cbox)
    form1.Controls.Add(btn)
    form1.Show()
    Dim wait As Boolean = True
    Do While wait
        If btn.Name = "Done" Then
            wait = False
        End If
    Loop
    Return cbox.SelectedIndex
End Function

Private Sub cboxSubmitPressed(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim btn As Button = CType(sender, Button)
    btn.Name = "Done"
End Sub

However, this causes the program to crash due to the obvious infinite loop. How can I make this work? I need to be able to get the user's selection at runtime because the options are obtained from a server using a POST request.

Thanks,

Paul

Upvotes: 1

Views: 552

Answers (1)

LarsTech
LarsTech

Reputation: 81655

Eliminate the wait loop and just use the dialog option:

If form1.ShowDialog() = DialogResult.OK Then
  return cbox.SelectedIndex
End If

For the button, setting the value of the DialogResult closes the dialog:

Private Sub cboxSubmitPressed(sender As Object, e As EventArgs)
  With DirectCast(CType(sender, Button).Parent, Form)
    .DialogResult = DialogResult.OK
  End With
End Sub

This value gets returned by the ShowDialog function call so you can check for it.

Upvotes: 1

Related Questions