在等待表单中的用户输入时避免无限循环

时间:2014-02-25 20:11:43

标签: vb.net input combobox

我正在尝试创建一个类似于InputBox函数的提示,它允许用户在运行时从数组中选择一个选项。以下是我到目前为止的情况:

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

但是,这会导致程序因明显的无限循环而崩溃。我怎样才能做到这一点?我需要能够在运行时获取用户的选择,因为选项是使用POST请求从服务器获得的。

谢谢,

1 个答案:

答案 0 :(得分:1)

消除等待循环,只需使用对话框选项:

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

对于该按钮,设置DialogResult的值将关闭对话框:

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

此值由ShowDialog函数调用返回,因此您可以检查它。