2014-02-25 119 views
1

我试图创建一个类似于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请求从服务器获取的。

感谢,

保罗

+0

你可以尝试声明昏暗的等待作为布尔=真的功能? – DevelopmentIsMyPassion

+0

@AshReva我试着在函数外面声明等待并简单地在事件处理函数中改变它的值,但是这并没有解决问题。 – Paul

+0

什么时候调用这个函数? – DevelopmentIsMyPassion

回答

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函数调用返回,因此您可以检查它。

+0

这工作得很好,除了我不得不将Me.DialogResult更改为sender.DialogResult – Paul